Mysql count return Zero if no record found

前端 未结 4 2051
一个人的身影
一个人的身影 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 20:49

    The query:

    SELECT cities.*, COUNT(properties.id_city) as num
    FROM cities
    LEFT JOIN properties on cities.id_city=properties.id_city
    GROUP BY cities.id_city
    

    should return a 0 count where you want it, although I'm not 100% certain it works that way in MySQL.

    0 讨论(0)
  • 2020-12-14 21:07

    Use an outer join:

    select cities.city_name, count(properties.id_city)
      from cities left join properties on cities.id_city = properties.id_city
      group by 1
    
    0 讨论(0)
  • 2020-12-14 21:15

    Simple. Use "(Count(*) + 0)". Any null plus 0 will return a number.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题