views:

1297

answers:

3

I have a two tables for ex:

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 return ZERO if no records founds istead on NULL

so I get results like

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

and NEW YORK is [0] not NULL, NOT 1

+4  A: 

Use an outer join:

select cities.city_name, count(properties.id_city)
  from cities left join properties on cities.id_city = property.id_city
  group by 1
ChssPly76
select cities.city_name, count(*) from cities left join properties on cities.id_city = properties.id_city group by 1
Preston
it's wrong!it gives back results with "1" even if there is no matches
David King
try count(properties.id_property) instead of count(*)
timdev
I've changed the query - take a look. Instead of count(*) you should use count(column from left joined table)
ChssPly76
NOW IT WORKS :)
David King
+1  A: 

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.

Larry Lustig
+1  A: 

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