Mysql count return Zero if no record found

馋奶兔 提交于 2019-11-28 20:43:47
ChssPly76

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

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);
Larry Lustig

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.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!