Mysql count group by 和 left join 未按预期工作
以下是点击跟踪链接的简单查询。我看了很多其他帖子,但我还是摸不着头脑。我无法让此查询工作,以便显示日历表中的所有行(每行一个日历日):
SELECT DATE_FORMAT(calendar_date, '%a %D') AS calendar_date,
count( tracker_id ) as clicks
FROM calendar
LEFT JOIN offer_tracker USING(calendar_id)
WHERE
calendar_month = Month(CURDATE()) AND
calendar_year = Year(CURDATE()) AND ( offer_id = 4 OR offer_id IS NULL )
GROUP BY calendar_date;
它几乎就在那里,但并非日历表中的所有行都返回,即没有星期五 2 日、星期二 6 日、星期三 7 日等:
有人对我哪里出错有任何想法吗?我应该使用子查询吗?
Below is a simple query for a click tracker. I've had a look at a lot of other posts and I'm scratching my head. I cannot get this query to work so that all rows from the calendar table (one calendar day per row) are displayed:
SELECT DATE_FORMAT(calendar_date, '%a %D') AS calendar_date,
count( tracker_id ) as clicks
FROM calendar
LEFT JOIN offer_tracker USING(calendar_id)
WHERE
calendar_month = Month(CURDATE()) AND
calendar_year = Year(CURDATE()) AND ( offer_id = 4 OR offer_id IS NULL )
GROUP BY calendar_date;
It's nearly there but not all rows in the calendar table are returned i.e. there is no Fri 2nd, Tue 6th, Wed 7th etc:
Does anyone have any ideas on where I'm going wrong? Should I be using a subquery?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜
offer_id
来自offer_tracker
表。当您有(左)外部联接,并且在WHERE
条件中使用右表中的字段(例如您的offer_id = 4
)时,联接实际上被取消并给出与内连接相同的结果。取消取消的尝试(
offer_id = 4 OR Offer_id IS NULL
)无法按您的预期进行。offer_tracker
中带有offer_id <> 的任何行4
已经通过了 LEFT JOIN,但由于 WHERE 条件而被删除。因此,如果该日期的offer_id
行与4
不同,则结果中不会出现Friday 2nd
行。将
offer_id = 4
检查移至LEFT JOIN
,而是:I guess the
offer_id
is from theoffer_tracker
table. When you have an (left) outer join, and you use a field from the right table in aWHERE
condition (like youroffer_id = 4
), the join is actually cancelled and gives same results as an inner join.The attempt to lift the cancellation (
offer_id = 4 OR offer_id IS NULL
) does not work as you expect. Any row fromoffer_tracker
withoffer_id <> 4
has already passed the LEFT JOIN but is removed because of the WHERE condition. So, no row withFriday 2nd
will appear in the results if there is a row withoffer_id
different than4
for this date.Move the
offer_id = 4
check to theLEFT JOIN
, instead: