从SQL中的EAV表转换

时间:2018-05-17 21:10:31

标签: sql entity-attribute-value

我有问题转换为EAV表的格式有用的东西。链接表让我困惑,我真的不知道如何开始解决这个问题。有人有建议吗?

联系人表

con_id Name Data
1      email a@gmail.com
2      phone 123
3      email b@gmail.com
4      phone 456

链接表(将实际用户帐户映射到Contacts表中的行):

acct_id con_id
1       1
1       2
2       3
2       4

结束目标:

acct_id Email       Phone
1       a@gmail.com 123
2       b@gmail.com 456

1 个答案:

答案 0 :(得分:0)

http://sqlfiddle.com/#!4/7cf20/5/0

CREATE TABLE Contacts
    (con_id int, Name varchar2(5), Data varchar2(11))
;

INSERT ALL 
    INTO Contacts (con_id, Name, Data)
         VALUES (1, 'email', 'a@gmail.com')
    INTO Contacts (con_id, Name, Data)
         VALUES (2, 'phone', '123')
    INTO Contacts (con_id, Name, Data)
         VALUES (3, 'email', 'b@gmail.com')
    INTO Contacts (con_id, Name, Data)
         VALUES (4, 'phone', '456')
SELECT * FROM dual
;

CREATE TABLE Link
    (acct_id int, con_id int)
;

INSERT ALL 
    INTO Link (acct_id, con_id)
         VALUES (1, 1)
    INTO Link (acct_id, con_id)
         VALUES (1, 2)
    INTO Link (acct_id, con_id)
         VALUES (2, 3)
    INTO Link (acct_id, con_id)
         VALUES (2, 4)
SELECT * FROM dual
;

查询 -

select * from (
select acct_id, name, Data
from contacts c, Link l
where c.con_id = l.con_id
)
pivot (max(Data) for name in ('email' as Email,'phone' as Phone));

输出 -

ACCT_ID EMAIL         PHONE
1       a@gmail.com   123
2       b@gmail.com   456