在 SQL 中从 EAV table 转换
Convert from an EAV table in SQL
我在将 EAV table 格式转换为有用的格式时遇到问题。 link table 让我感到困惑,我真的不知道如何开始解决这个问题。有人有建议吗?
联系人table
con_id Name Data
1 email a@gmail.com
2 phone 123
3 email b@gmail.com
4 phone 456
Link table(将实际用户帐户映射到联系人 table 中的行):
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
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
我在将 EAV table 格式转换为有用的格式时遇到问题。 link table 让我感到困惑,我真的不知道如何开始解决这个问题。有人有建议吗?
联系人table
con_id Name Data
1 email a@gmail.com
2 phone 123
3 email b@gmail.com
4 phone 456
Link table(将实际用户帐户映射到联系人 table 中的行):
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
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