Mysql的计数返回零,如果没有找到记录(Mysql count return Zero if no

2019-07-21 04:59发布

我有两个表。

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

我想显示cities.city_name和它旁边[properties.count(id_city)]

如何进行查询,如果不找到任何记录,而不是仍然返回零NULL ,让我得到这样的结果:

London [123]
New York [0]
Berlin [11]

其中,“纽约”是[0],没有NULL ,而不是1?

Answer 1:

使用外连接:

select cities.city_name, count(properties.id_city)
  from cities left join properties on cities.id_city = properties.id_city
  group by 1


Answer 2:

我想下面就为你做,虽然我没有测试它。 关键是要获得属性计数一个表,然后向左加入该表到城市表,采用转换NULL值到0 IFNULL功能。

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


Answer 3:

查询:

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

应该返回你想让它一个0计数,虽然我不是100%肯定它工作在MySQL的方式。



Answer 4:

简单。 使用 “(COUNT(*)+ 0)”。 任何空加0将返回一个数字。



文章来源: Mysql count return Zero if no record found
标签: mysql zero