左边加入Count和Where子句的Where子句

时间:2016-09-30 04:02:45

标签: mysql sql

我有以下查询:

SELECT G.groupCode, G.groupName, COUNT(C.cdCode) AS numberOfTops10CDs FROM musicalgroup G 
    LEFT OUTER JOIN cd C ON C.groupCode = G.groupCode
    WHERE C.cdCode IN 
        (SELECT cdCode FROM topcds WHERE rating <= 10)
GROUP BY G.groupCode

在这种情况下,如果关联的计数为0,它不显示组。我希望这显示音乐组中的每个元素,即使计数为0。 当我这样做时:

 SELECT G.groupCode, G.groupName, COUNT(C.cdCode) AS numberOfTops10CDs FROM musicalgroup G 
     LEFT OUTER JOIN cd C ON C.groupCode = G.groupCode
     GROUP BY G.groupCode

它显示即使计数为0,但我只需要显示评分低于10的CD。如何在一个查询中完成这两个目标?

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT G.groupCode,
       G.groupName,
       COUNT(C.cdCode) AS numberOfTops10CDs 
FROM musicalgroup G 
LEFT OUTER JOIN cd C
    ON C.groupCode = G.groupCode AND
       C.cdCode in (SELECT distinct cdCode FROM topcds WHERE rating <= 10)
GROUP BY G.groupCode,G.groupName

答案 1 :(得分:0)

我认为这样的事情就像你想要做的那样。下面的查询使用条件聚合来计算每个音乐组中评级大于10的CD数量。它避免了使用WHERE子句的问题,该子句可以删除要用于结果集的记录

SELECT g.groupCode,
       SUM(CASE WHEN c.cdCode IN
           (SELECT cdCode FROM topcds WHERE rating > 10) THEN 1 END) AS numberOfTops10CDs
FROM musicalgroup g
LEFT JOIN cd c
    ON g.groupCode = c.groupCode
GROUP BY g.groupCode