Mysql count return Zero if no record found

前端 未结 4 2058
一个人的身影
一个人的身影 2020-12-14 20:40

I have a two tables.

cities - id_city, city_name
properties - id_property, id_city, property_name

I want to display cities.city_name<

4条回答
  •  渐次进展
    2020-12-14 21:16

    I think the following will do it for you, though I haven't tested it. The trick is to get the property counts in one table, and then to left join that table to the cities table, converting NULLs to 0s using the IFNULL function.

    SELECT city_name, IFNULL(property_count, 0)
    FROM cities
    LEFT JOIN
       (SELECT id_city, count(*) as property_count
        FROM properties
        GROUP BY id_city) city_properties
       USING (id_city);
    

提交回复
热议问题