问题
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
=======================================
| 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.
回答1:
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 ;
来源:https://stackoverflow.com/questions/7034212/mysql-how-to-convert-to-eav-part-2