城镇报告(订单数量)

时间:2011-06-06 16:38:03

标签: mysql sql select report

我正在按照城镇创建报告。

SELECT S.city, count(*) as NumOfOrders
    FROM Shop as S
    LEFT JOIN orders O ON O.ShopID = S.ShopID
WHERE O.status = 4
Group by S.city

结果显示如下:

Town 1  |   53
Town 2  |   45
Town 3  |   64

它工作正常,但我想显示所有城镇甚至没有订单?

预期结果:

Town 1  |   53
Town 2  |   45
Town 3  |   64
Town 4  |   0
Town 5  |   0

我已经尝试将LEFT JOIN替换为RIGHT JOIN,这甚至都不起作用。结果相同。

4 个答案:

答案 0 :(得分:6)

您的过滤器不包括没有订单的过滤器。尝试将条件纳入联接,你应该没事。

SELECT S.city, count(O.any_non_nullable_field) as NumOfOrders
    FROM Shop as S
    LEFT JOIN orders O ON (O.ShopID = S.ShopID AND O.status = 4)
Group by S.city

答案 1 :(得分:1)

虽然您正在使用LEFT JOIN,但您在Where子句中使用o.statu列,因此将删除具有空值(左连接的cos)的行。

试试这个:

SELECT S.city, 
        SUM 
        (
        CASE 
            WHEN ISNULL(O.status) THEN 0
            ELSE 1
        END  
        ) as NumOfOrders     
    FROM Shop as S  LEFT JOIN orders O 
      ON O.ShopID = S.ShopID 
 WHERE IFNULL(O.status, 4) = 4 
    GROUP BY S.city 

答案 2 :(得分:0)

它可能不是最干净的方法,但将上述查询包装到子查询中并保持连接到Shop表可以。

SELECT s.city, IfNull(x.NumOfOrders, 0)
FROM Shop as s
LEFT JOIN (
    SELECT S.city, count(*) as NumOfOrders
    FROM Shop as S
    LEFT JOIN orders O ON O.ShopID = S.ShopID
    WHERE O.status = 4
    Group by S.city
) x
ON s.city = x.city

答案 3 :(得分:-1)

您正在正确地进行外部连接,但是您的WHERE子句中的条件是O.status必须为4。