MYSQL: COUNT with GROUP BY, LEFT JOIN and WHERE clause doesn't return zero values
- by Paul Norman
Hi guys, thanks in advance for any help on this topic!
I'm sure this has a very simply answer, but I can't seem to find it (not sure what to search on!). A standard count / group by query may look like this:
SELECT COUNT(`t2`.`name`)
FROM `table_1` `t1`
LEFT JOIN `table_2` `t2` ON `t1`.`key_id` = `t2`.`key_id`
GROUP BY `t1`.`any_col`
and this works as expected, returning 0 if no rows are found. So does:
SELECT COUNT(`t2`.`name`)
FROM `table_1` `t1`
LEFT JOIN `table_2` `t2` ON `t1`.`key_id` = `t2`.`key_id`
WHERE `t1`.`another_column` = 123
However:
SELECT COUNT(`t2`.`name`)
FROM `table_1` `t1`
LEFT JOIN `table_2` `t2` ON `t1`.`key_id` = `t2`.`key_id`
WHERE `t1`.`another_column` = 123
GROUP BY `t1`.`any_col`
only works if there is at least one row in table_1 and fails miserably returning an empty result set if there are zero rows. I would really like this to return 0! Anyone enlighten me on this? Beer can be provided in exchange if you are in London ;-)