使用 switch case 连接两个表以避免一对多连接

Join two tables with switch case in order to avoid one to many join

我有两个 table,t1t2

Table t1:

Name address id
---- ------- --
rob  32 cgr  12
mary 31 lmo  42
tom  axel St 2

Table t2:

ID Flag expense
-- ---- --------
12 Shop 1200
12 Educ 14000
42 educ 4000

现在我必须创建一个 table,它将具有来自 t1 的属性以及另外两个属性,即 shop 中的费用和 educ 中的费用

Table 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

如何实现?

我尝试使用 switch case 执行左连接 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 table,才能在标志的基础上有一条记录。但我不知道该怎么做。

请注意 table 很大,优化查询会很好。

求推荐。

你只需要加入第一个table到第二个,两次:

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'

Demo