return count 0 with mysql group by

后端 未结 4 875
死守一世寂寞
死守一世寂寞 2020-12-06 17:46

database table like this

============================
= suburb_id   |   value
= 1           |    2
= 1           |    3
= 2           |    4
= 3           |          


        
4条回答
  •  感动是毒
    2020-12-06 18:42

    A GROUP BY needs rows to work with, so if you have no rows for a certain category, you are not going to get the count. Think of the where clause as limiting down the source rows before they are grouped together. The where clause is not providing a list of categories to group by.

    What you could do is write a query to select the categories (suburbs) then do the count in a subquery. (I'm not sure what MySQL's support for this is like)

    Something like:

    SELECT 
      s.suburb_id,
      (select count(*) from suburb_data d where d.suburb_id = s.suburb_id) as total
    FROM
      suburb_table s
    WHERE
      s.suburb_id in (1,2,3,4)
    

    (MSSQL, apologies)

提交回复
热议问题