从SQL中的select语句中提取多个值

时间:2013-02-22 19:51:41

标签: sql select inner-join

我正在努力以更有效和更优雅的方式实现这一目标

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 Postcode,但是当PostcodeData.postcode中不存在MemberDetail.postcode时,我遇到了问题。在这种情况下,我仍然希望选择那些成员但是对于City,State和Areacode具有NULL结果。这是在当前查询中实现的,但效率非常低。任何想法,将不胜感激。干杯!

3 个答案:

答案 0 :(得分:4)

只需使用LEFT JOIN

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

答案 1 :(得分:0)

使用OUTER JOIN代替INNER JOIN - 即使连接表上没有匹配的记录,也会返回记录。

  

然后,外连接将返回FROM子句中提到的至少一个表或视图中的所有行,只要这些行满足任何WHERE或HAVING搜索条件。

答案 2 :(得分: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