SQL-如何连接表和那些空值,特别是使用连接表中的一个项目?
问题描述:
请检查以下表格:SQL-如何连接表和那些空值,特别是使用连接表中的一个项目?
当表1左列表项2连接到表项2时,对于梨和橙色,Coef列将为空。我怎样才能让表格2中的ItemName = 其他匹配所有非映射项目?
目前,我正在使用临时表来过滤那些空的项目,把正确的COEF,然后联盟与映射项结果得到最终的表3
有没有更好的方式来实现这一目标?
表1:
ItemName | Cost |
Apple | 1 |
Banana | 2 |
Pear | 3 |
Orange | 4 |
表2:
ItemName | Coef |
Apple | 0.1 |
Banana | 0.2 |
Others | 0.8 |
预期结果:
ItemName | Cost | Coef |
Apple | 1 | 0.1 |
Banana | 2 | 0.2 |
Pear | 3 | 0.8 |
Orange | 4 | 0.8 |
答
你可以cross join
与单列你的结果和采取的第一个非空价值:
SELECT t1.itemname, t1.cost, COALESCE(t2.coef, def.coef)
FROM t1
LEFT JOIN t2 ON t1.itemname = t2.itemname
CROSS JOIN (SELECT coef
FROM t2
WHERE itemname = 'Others') def
的数据库是你真正使用中,MySQL或SQL Server?请标记corectly –