MySQL: how to convert to EAV?

南楼画角 提交于 2019-12-04 01:41:00

问题


Say I have the following table:

TABLE: one
===============================
| id | first_name | last_name |
===============================
| 1  | John       | Doe       |
| 2  | Jane       | Smith     |
-------------------------------

I want to convert it to an EAV:

TABLE: two
===================================
| id | fk_id | attribute  | value |
===================================
| 1  | 1     | first_name | John  |
| 2  | 1     | last_name  | Doe   |
| 3  | 2     | first_name | Jane  |
| 4  | 2     | last_name  | Smith |
-----------------------------------

Note:

  • two.fk_id values came from one.id
  • two.attribute values came from one.first_name
  • two.value values came from one.last_name

I need to create table two from table one so I can run some tests.


回答1:


I'm assuming two.id is an autoincrementing integer, so I'll leave it to the target table to assign those values.

select id as fk_id, 'first_name' as attribute, first_name as value
from one
union all
select id as fk_id, 'last_name', last_name
from one
order by fk_id, attribute



回答2:


For the love of god, don't use EAV!!!! If you need that, use a NoSQL database instead!



来源:https://stackoverflow.com/questions/7020661/mysql-how-to-convert-to-eav

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