MS Access SQL记录在LEFT JOIN中消失,不应该

时间:2016-08-17 22:58:30

标签: sql ms-access

我真的不明白为什么这个LEFT JOIN没有按照应有的方式运作。应该有来自cleaning_zzz_2016的99条记录,就像我删除LEFT JOIN时的情况一样。但是,当我添加LEFT JOIN时,它会下降到96. CoNumber表中不存在cleaning_zzz_sales的某些内容,所以我希望这些字段只是空白的要保留的s.数据;然而,它正在删除它们。我认为这可能是由于WHERE s.Rep = 'ZZZ',但我不是百分百肯定或如何解决这个问题。

SELECT j.CoNumber, j.CoName, s.Selling, s.Positions, s.Plans, '' AS Review, j.St, j.CE, j.SI, j.Tgt, ROUND(MAX(j.Comm) * 100) AS [Max of Comm], ROUND(MAX(j.Comm2) * 100) AS [Max of Comm2]
FROM cleaning_zzz_2016 AS j 
LEFT JOIN cleaning_zzz_sales AS s 
  ON j.CoNumber= s.CoNumber
WHERE s.Rep = 'ZZZ' AND s.RepYear = 2016
GROUP BY j.CoNumber, j.CoName, j.St, j.CE, j.SI, j.Tgt, s.Selling, s.Positions, s.Plans
ORDER BY j.CoNumber;

3 个答案:

答案 0 :(得分:3)

where子句中的任何条件都将直接过滤掉行。您希望直接在连接条件本身中添加左连接表的所有条件。使用MS Access,我相信当您有多个连接条件时,需要注意括号。

所以我认为查询看起来像这样:

SELECT j.CoNumber, j.CoName, s.Selling, s.Positions, s.Plans, '' AS Review, j.St, j.CE, j.SI, j.Tgt, ROUND(MAX(j.Comm) * 100) AS [Max of Comm], ROUND(MAX(j.Comm2) * 100) AS [Max of Comm2]
FROM cleaning_zzz_2016 AS j 
LEFT JOIN cleaning_zzz_sales AS s 
  ON (j.CoNumber= s.CoNumber
  AND s.Rep = 'ZZZ' 
  AND s.RepYear = 2016)
GROUP BY j.CoNumber, j.CoName, j.St, j.CE, j.SI, j.Tgt, s.Selling, s.Positions, s.Plans
ORDER BY j.CoNumber;

答案 1 :(得分:1)

是的,您不应该使用where右侧的left join列。只需将这些条件放在ON

上即可

答案 2 :(得分:1)

问题是where子句中的列。不幸的是,MS Access不允许在on中进行持续比较。您可以使用子查询修复此问题:

SELECT j.CoNumber, j.CoName, s.Selling, s.Positions, s.Plans,
       '' AS Review, j.St, j.CE, j.SI, j.Tgt,
       ROUND(MAX(j.Comm) * 100) AS [Max of Comm],
       ROUND(MAX(j.Comm2) * 100) AS [Max of Comm2]
FROM cleaning_zzz_2016 AS j LEFT JOIN
     (SELECT s.*
      FROM cleaning_zzz_sales AS s 
      WHERE s.Rep = 'ZZZ' AND s.RepYear = 2016
     ) s
     ON j.CoNumber= s.CoNumber
GROUP BY j.CoNumber, j.CoName, j.St, j.CE, j.SI, j.Tgt, s.Selling, s.Positions, s.Plans
ORDER BY j.CoNumber;