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 | 
+0

的数据库是你真正使用中,MySQL或SQL Server?请标记corectly –

你可以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 
+0

次要拼写:'itername' =>'itemname' – tonypdmtr

+0

@tonypdmtr编辑和固定 - 感谢注意到 – Mureinik

+0

伟大的作品! Thx – Spencer

您可以使用两个左联接:

select t1.*, 
     coalesce(t2.coef, t2o.coef) as coef 
from t1 left join 
    t2 
    on t1.itemname = t2.itemname left join 
    t2 t2o 
    on t2o.itemname = 'Others'; 
+0

小拼字:''others'' =>''其他' – tonypdmtr

+0

很棒!谢谢 – Spencer