2011-08-11 22 views
3

說我有如下表:MySQL:如何轉換爲EAV?

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

我想將它轉換爲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 | 
----------------------------------- 

注:

  • two.fk_id值從one.id
  • 來到
  • two.attribute values from one.first_name
  • two.value v alues來自one.last_name

我需要從表一創建表二,所以我可以運行一些測試。

回答

0

我假設two.id是一個autoincrementing整數,所以我將它留給目標表來分配這些值。

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 
0

對於上帝的愛,不要使用EAV !!!! 如果您需要,請使用NoSQL數據庫!

+7

對不起,這不是關於EAV的優點和缺點的問題。我只需要知道如何將表格1轉換成表格2。 – StackOverflowNewbie