SQL 加入行 table 和列 table

SQL Join a row table with a column table

我有两个 table 正在尝试连接(加入)。 Table1是一列table如下:

id Phone Name Description
101 123456 Maria Abc
102 234567 Daniel Def

Table2是一行table如下:

id Attribute Value
101 Manager Rudolf
101 Account 456
101 Code B
102 Manager Anna
102 Code B
102 Code C

我要找的结果是:

id Phone Name Description Manager Account Code
101 123456 Maria Abc Rudolf 456 B
102 234567 Daniel Def Anna B,C

您可以加​​入同一个 table 三次(使用不同的别名)。例如:

select
  p.*,
  a.value as Manager,
  b.value as Account,
  c.value as Cardno
from table1 p
left join table2 a on a.id = p.id and a.attribute = 'Manager'
left join table2 b on b.id = p.id and b.attribute = 'Account'
left join table2 c on c.id = p.id and b.attribute = 'Cardno'

你应该使用 3 次 table 2 来获取 manager 的 3 个属性 inner(始终匹配)和 left join 用于 Account 和 CardNo(不总是匹配)

select a.id, a.phone, a.Name, a.Description b.value, c.value
from table1 a 
inner join table2 b ON a.id = b.id and b.attribute = 'Manager' 
left  join table2 c ON a.id = c.id and c.attribute = 'Account' 
left join table2 d ON a.id = d.id and d.attribute = 'CardNo' 

如果您的“行 table”中只有三个唯一属性,那么您可以使用这样的子查询:

SELECT 
t.*,
(SELECT t2.Value FROM Table2 WHERE t2.id = t1.id AND t2.Attribute='Manager') as Manager,
(SELECT t2.Value FROM Table2 WHERE t2.id = t1.id AND t2.Attribute='Account') as Account, 
(SELECT t2.Value FROM Table2 WHERE t2.id = t1.id AND t2.Attribute='Cardno') as Cardno,
FROM Table1 t

如果您有更多独特的属性,那么您应该尝试 views or stored procedure 和临时 table 来生成您想要的 table