问题
I have a two tables.
cities - id_city, city_name
properties - id_property, id_city, property_name
I want to display cities.city_name
and next to it [properties.count(id_city)]
How do I make a query that still returns zero if no records are found instead of NULL
, so that I get results like this:
London [123]
New York [0]
Berlin [11]
where "New York" is [0], not NULL
and not 1?
回答1:
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
回答2:
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);
回答3:
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.
回答4:
Simple. Use "(Count(*) + 0)". Any null plus 0 will return a number.
来源:https://stackoverflow.com/questions/1528688/mysql-count-return-zero-if-no-record-found