开发者

MySQL: how to convert to EAV - Part 2?

Here's Part 1: MySQL: how to convert to EAV?

Now I want to also do something different. Say I have the following table:

TABLE: one
=======================================
开发者_JAVA技巧| id | fk_id | attribute  | value     |
=======================================
| 1  | 10    | first_name | John      |
| 2  | 10    | last_name  | Doe       |
| 3  | 55    | first_name | Bob       |
| 4  | 55    | last_name  | Smith     |
---------------------------------------

I want to convert it to this EAV model:

TABLE: attribute
===================
| id | attribute  |
===================
| 1  | first_name |
| 2  | last_name  |
-------------------

TABLE: value
=====================================
| id | attribute_id | fk_id | value |
=====================================
| 1  | 1            | 10    | John  |
| 2  | 2            | 10    | Doe   |
| 3  | 1            | 55    | Bob   |
| 4  | 2            | 55    | Smith |
-------------------------------------

Assume the tables attribute and value are already defined. How do I insert the data from table one into the two target tables. One big problem for me is how to get the relationship (attribute.id => value.attribute_id) right.


INSERT INTO attribute
  (attribute)
SELECT DISTINCT
  attribute
FROM one ;

INSERT INTO value
  (attribute_id, fk_id, value)
SELECT 
  attribute.id, one.fk_id, one.value
FROM one
  JOIN attribute
    ON attribute.attribute = one.attribute ;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜