左连接显示所有行

时间:2012-04-12 16:05:35

标签: mysql left-join

SELECT 
    CH.ChannelName, COUNT(O.OrderID) AS Orders
FROM
    Channels CH
LEFT JOIN Programs P USING (ChannelID)
LEFT JOIN Codes C USING (ProgramID)
LEFT JOIN Order O USING (CodeID)
WHERE
    O.OrderDate = '2012-04-11'
GROUP BY 
    CH.ChannelName
WITH ROLLUP

此查询仅返回包含订单的渠道。即使该特定频道的订单表中没有订单,我如何显示所有频道?基本上,所有频道都会被列出,如果该频道没有订单,我需要显示零。

我知道对此的解决方案可能非常简单。谢谢你的帮助。

3 个答案:

答案 0 :(得分:0)

您的where子句将查询限制为具有该日期订单的渠道,但如果您将该条件移至join语句,它将为您提供所需的结果:

SELECT 
    CH.ChannelName, COUNT(O.ID) AS Orders
FROM
    Channels CH
LEFT JOIN Programs P USING (ChannelID)
LEFT JOIN Codes C USING (ProgramID)
LEFT JOIN Order O ON CH.CodeID = O.CodeID AND O.OrderDate = '2012-04-11'
GROUP BY 
    CH.ChannelName
WITH ROLLUP

注意,它应该COUNT(O.ID)使SQL只计算具有非空订单的行。在这种情况下,对于没有订单的渠道,您将正确获得零订单数。

答案 1 :(得分:0)

SELECT 
    CH.ChannelName, COUNT(O.OrderID) AS Orders
FROM
    Channels CH
LEFT JOIN Programs P USING (ChannelID)
LEFT JOIN Codes C USING (ProgramID)
LEFT OUTER JOIN Order O USING (CodeID)
WHERE
    O.OrderDate = '2012-04-11'
GROUP BY 
    CH.ChannelName
WITH ROLLUP

答案 2 :(得分:0)

试试这个:

SELECT CH.ChannelName, SUM(O.OrderDate = '2012-04-11') AS Orders
FROM Channels CH
LEFT JOIN Programs P USING (ChannelID)
LEFT JOIN Codes C USING (ProgramID)
LEFT JOIN Order O USING (CodeID)
GROUP BY CH.ChannelName
WITH ROLLUP