sql - MYSQL: COUNT with GROUP BY, LEFT JOIN and WHERE clause doesn't return zero values -


i'm sure has simple answer, can't seem find (not sure search on!). standard count / group query may this:

select count(`t2`.`name`)  `table_1` `t1`      left join `table_2` `t2` on `t1`.`key_id` = `t2`.`key_id`  `t1`.`another_column` = 123  

and works expected, returning 0 if no rows found. however:

select count(`t2`.`name`)  `table_1` `t1`      left join `table_2` `t2` on `t1`.`key_id` = `t2`.`key_id`  `t1`.`another_column` = 123  group `t1`.`any_col`  

only works if there @ least 1 row in table_1 , fails miserably returning empty result set if there 0 rows. return 0! enlighten me on this? beer can provided in exchange if in london ;-)

the reason returns 0 rows grouping on value in table_1. since there no values in table_1, there no rows return. said way, if returned t1.any_col in query group so:

select `t1`.`any_col`, count(`t2`.`name`)  `table_1` `t1`      left join `table_2` `t2` on `t1`.`key_id` = `t2`.`key_id`  `t1`.`another_column` = 123  group `t1`.`any_col`  

what display t1.any_col when there no rows? way achieve want union results query checks no rows in table_1. in example, i'm using information_schema view have against can query.

select count(`t2`.`name`)  `table_1` `t1`      left join `table_2` `t2` on `t1`.`key_id` = `t2`.`key_id`  `t1`.`another_column` = 123  group `t1`.`any_col`  union select 0 information_schema.tables not exists( select 1 `table_1` ) limit 1 

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -