return count 0 with mysql group by

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

database table like this

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


        
4条回答
  •  -上瘾入骨i
    2020-12-06 18:39

    This:

    SELECT  id, COUNT(suburb_id)
    FROM    (
            SELECT  1 AS id
            UNION ALL
            SELECT  2 AS id
            UNION ALL
            SELECT  3 AS id
            UNION ALL
            SELECT  4 AS id
            ) ids
    LEFT JOIN
            suburbs s
    ON      s.suburb_id = ids.id
    GROUP BY
            id
    

    or this:

    SELECT  id,
            (
            SELECT  COUNT(*)
            FROM    suburb
            WHERE   suburb_id = id
            )
    FROM    (
            SELECT  1 AS id
            UNION ALL
            SELECT  2 AS id
            UNION ALL
            SELECT  3 AS id
            UNION ALL
            SELECT  4 AS id
            ) ids
    

    This article compares performance of the two approaches:

    • Aggregates: subqueries vs. GROUP BY

    , though it does not matter much in your case, as you are querying only 4 records.

提交回复
热议问题