Mysql count group by and left join not working as expected
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 开发者_JS百科ideas on where I'm going wrong? Should I be using a subquery?
I guess the offer_id
is from the offer_tracker
table. When you have an (left) outer join, and you use a field from the right table in a WHERE
condition (like your offer_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 from offer_tracker
with offer_id <> 4
has already passed the LEFT JOIN but is removed because of the WHERE condition. So, no row with Friday 2nd
will appear in the results if there is a row with offer_id
different than 4
for this date.
Move the offer_id = 4
check to the LEFT JOIN
, instead:
SELECT DATE_FORMAT(calendar_date, '%a %D') AS calendar_date
, count( tracker_id ) as clicks
FROM calendar
LEFT JOIN offer_tracker
ON offer_tracker.calendar_id = calendar.calendar_id
AND offer_id = 4
WHERE calendar_month = Month(CURDATE())
AND calendar_year = Year(CURDATE())
GROUP BY calendar_date
精彩评论