使用GROUP BY的LEFT JOIN不返回预期的LEFT JOIN结果

时间:2019-04-16 07:57:08

标签: mysql group-by left-join

我正在尝试获取每个商店的所有累积销售额,即使该值为null(条件无顺序),但LEFT JOIN只给我具有对应关系的行,这不适合我:

SELECT s.identifierExt as StoreID, 
YEAR(o.creation) AS Year,
MONTHNAME(o.creation) AS Month,
MONTH(o.creation) AS IDMonth,
ROUND(SUM(o.price), 2) AS Sales
FROM store s
LEFT JOIN order o ON o.store = s.id 
AND (o.creation < '2018-09-13 00:00:00') 
AND (o.place NOT IN ('PENDING','CANCELLED')) 
AND (o.creation > '2018-01-12 00:00:00')
GROUP BY Year, Month, StoreID
ORDER BY IDMonth, StoreID ASC

谢谢。

1 个答案:

答案 0 :(得分:0)

可能是因为INNEROUTER连接之间的差异。内部联接要求有一个对应的行(联接条件匹配),外部联接没有这样的要求:它将返回带有NULL的列。

似乎您想加入OUTER:

SELECT s.identifierExt as StoreID, 
YEAR(o.creation) AS Year,
MONTHNAME(o.creation) AS Month,
MONTH(o.creation) AS IDMonth,
ROUND(SUM(o.price), 2) AS Sales
FROM store s
LEFT OUTER JOIN order o ON o.store = s.id 
AND (o.creation < '2018-09-13 00:00:00') 
AND (o.place NOT IN ('PENDING','CANCELLED')) 
AND (o.creation > '2018-01-12 00:00:00')
GROUP BY Year, Month, StoreID
ORDER BY IDMonth, StoreID ASC

这样,您还将获得没有订单的 个商店。

另请参见this answer on the difference between inner and outer joins