我有两个表,t1
和t2
。
表t1:
Name address id
---- ------- --
rob 32 cgr 12
mary 31 lmo 42
tom axel St 2
表t2:
ID Flag expense
-- ---- --------
12 Shop 1200
12 Educ 14000
42 educ 4000
现在我需要创建一个表它将包含t1中的属性加上另外两个属性即shop中的费用和educ中的费用
表t3
Name address id Shop_ex Educ_ex
---- ------- -- ------- -------
rob 32 cgr 12 1200 14000
mary 31 lmo 42 NULL 4000
tom axel st 2 NULL NULL
如何做到这一点?
我尝试做一个左连接t2与开关情况下,但它给了我多个记录,因为连接正在成为一对多。
select
t1.name, t1.address, t1.id,
case
when t2.flag = "shop" then t2.expense
else null
end as shop_ex
case
when t2.flag = "educ" then t2.expense
else null
end as educ_ex
from
t1
left join
t2 on (t1.id = t2.id)
看来我将不得不转换t2表加入之前,有一个单一的记录的基础上的标志。但我不知道该怎么做。
请注意表是巨大的,优化查询将是很好的。
请建议。
您只需要将第一个表连接到第二个表,两次:
SELECT t1.Name, t1.address, t1.id, t2a.expense AS Shop_ex, t2b.expense AS Educ_ex
FROM table1 t1
LEFT JOIN table2 t2a
ON t2a.ID = t1.id AND t2a.Flag = 'Shop'
LEFT JOIN table2 t2b
ON t2b.ID = t1.id AND t2b.Flag = 'Educ'
演示