2017-11-25 153 views
1

請檢查以下表格: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 –

回答

3

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

3

您可以使用兩個左聯接:

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