这是第 1 部分:MySQL: how to convert to EAV?
现在我也想做一些不同的事情。假设我有下表:
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 |
---------------------------------------
我想把它转换成这个 EAV 模型:
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 |
-------------------------------------
假设表 attribute
和 value
已经定义。如何将表 one
中的数据插入到两个目标表中。对我来说,一个大问题是如何使关系 (attribute.id
=> value.attribute_id
) 正确。
最佳答案
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 ;
关于MySQL:如何转换为 EAV - 第 2 部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7034212/