我有两个表。
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?
使用外连接:
select cities.city_name, count(properties.id_city)
from cities left join properties on cities.id_city = properties.id_city
group by 1
我想下面就为你做,虽然我没有测试它。 关键是要获得属性计数一个表,然后向左加入该表到城市表,采用转换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);
查询:
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的方式。
简单。 使用 “(COUNT(*)+ 0)”。 任何空加0将返回一个数字。