2013-02-22 103 views
3

我想更有效地實現這一目標而優雅從select語句在SQL

SELECT 
    MD.*, 
    (SELECT City FROM PostcodeData WHERE MD.Postcode = Postcode) [City], 
    (SELECT State FROM PostcodeData WHERE MD.Postcode = Postcode) [State], 
    (SELECT Areacode FROM PostcodeData WHERE MD.Postcode = Postcode) [Areacode] 
FROM MemberDetails AS MD 

我能明顯INNER JOIN ON郵編兩個表,但我有問題時,MemberDetail.postcode確實拉動多個值不存在於PostcodeData.postcode中。在這種情況下,我仍然希望選擇這些成員,但對於城市,州和Areacode的結果爲NULL。這在當前查詢中已經實現,但效率很低。任何想法,將不勝感激。乾杯!

回答

4

只需使用一個LEFT JOIN

SELECT 
    MD.*, 
    P.City, 
    P.State, 
    P.Areacode 
FROM MemberDetails AS MD 
    LEFT JOIN PostcodeData P ON MD.Postcode = P.Postcode 
+0

乾杯@sgegges,左加入是我之後 – Gregology 2013-02-22 20:08:55

0

使用OUTER JOIN而不是INNER JOIN - 即使連接表上沒有匹配的記錄,它也會返回記錄。

但是,外部連接返回FROM子句中提到的至少一個表或視圖的所有行,只要這些行滿足任何WHERE或HAVING搜索條件。

0

肯定外連接就是答案?就像:

SELECT MD.*, 
IsNull(pc.City,"No city") AS City, 
IsNull(pc.State,"No state") AS State, 
IsNull(pc.AreaCode,"No area code") AS AreaCode 
FROM 
MemberDetails AS MD 
LEFT OUTER JOIN PostCodeData AS pc ON md.PostCode=pc.PostCode