更改此查询,以便在该值不存在时返回NULL行,否则返回该值

时间:2011-06-27 21:50:52

标签: sql join null

SELECT
    WCC.WardCensusTypesId, M.MonthsId, WCT.WardCensusTypesName,
    Y.YearsId, WCC.WardCensusCountsNum
FROM WardCensusTypes WCT
LEFT JOIN WardCensusCounts WCC ON 1=1
LEFT JOIN Months M ON 1=1
LEFT JOIN Years Y On Y.YearsId=3

WardCensusTypes 包含所有类型(其中6个)

月份仅包含月份列表(1-12)

包含格式化年份(yearsid = 1:'2010-2011',yearsid = 2:'2011-2012',依此类推)

WardCensusCounts 包含每个的WardCensusCountsNum,给定monthid,YearsId和WardCensusTypesId。

WardCensusCounts包含1条记录:WardCensusTypesId = 1,MonthsId = 1,YearsId = 3,WardCensusCountsNum = 5

当我执行上面的大查询时,我为每行获得WCC.WardCensusCountsNum的'10',查询返回72行,WCT.WardCensusCountsNum字段的值均为10。我想要的是匹配MonthsId,YearsId和WardCensusTypesId的1行的值10,但所有其他行(其中71个)应该为该字段返回NULL。有没有办法更改查询来执行此操作?

1 个答案:

答案 0 :(得分:2)

我认为您只需LEFT JOIN来表WardCensusCounts。由于您需要其他3个表的所有组合,这3个表中的CROSS JOIN更可能是您所需要的:

SELECT
    WCT.WardCensusTypesId            --- chnaged this to WCT. (not WCC.)
  , M.MonthsId
  , WCT.WardCensusTypesName 
  , Y.YearsId
  , WCC.WardCensusCountsNum
FROM
    WardCensusTypes WCT
  CROSS JOIN
    Months M 
  CROSS JOIN
    Years Y
  LEFT JOIN
    WardCensusCounts WCC
      ON  WCC.WardCensusTypesId = WCT.WardCensusTypesId
      AND WCC.MonthsId = M.MonthsId 
      AND WCC.YearsId = Y.YearsId
WHERE Y.YearsId = 3

关于CROSS JOIN

SELECT *
FROM 
    a
  CROSS JOIN
    b

也可以编码(可能是对于没有CROSS JOIN的旧dbms):

SELECT *
FROM 
    a
  , b

或者喜欢你所拥有的(因为1=1总是如此,如果你有JOIN或LEFT JOIN没有区别):

SELECT *
FROM 
    a
  JOIN
    b
  ON 1=1