MySQL: how to convert to EAV - Part 2?

被刻印的时光 ゝ 提交于 2019-12-08 05:09:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!