MYSQL: COUNT with GROUP BY, LEFT JOIN and WHERE clause doesn't return zero values
Posted
by Paul Norman
on Stack Overflow
See other posts from Stack Overflow
or by Paul Norman
Published on 2010-04-28T14:19:52Z
Indexed on
2010/04/28
14:23 UTC
Read the original article
Hit count: 150
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 ;-)
© Stack Overflow or respective owner