views:

33

answers:

1

Hi All, i am trying to create a query where there is a count of related records from another table. I'd like the "parent" records whether there are related records (a count) or not.

SELECT r.region_name, r.region_id, r.abbreviation, r.map_order,
    (IFNULL( COUNT( p.property_id ) , 0 )) AS propertyCount
FROM  `rmp_region` r
LEFT OUTER JOIN  `rmp_property` p 
    ON p.path LIKE CONCAT(  '%/', r.region_id,  '/%' ) 
WHERE p.active =1
AND r.parent_region_id =1
GROUP BY r.region_name, r.region_id, r.abbreviation, r.map_order
ORDER BY r.map_order ASC 

I've tried different variations of this.. but i cannot get the parent records to display if the count is zero/no related records.

thanks for any help!

A: 

You need to move "p.active = 1" from the WHERE clause into the OUTER JOIN criteria.

Here's your example with the change:

SELECT r.region_name, r.region_id, r.abbreviation, r.map_order,
    (IFNULL( COUNT( p.property_id ) , 0 )) AS propertyCount
FROM  `rmp_region` r
LEFT OUTER JOIN  `rmp_property` p 
    ON p.path LIKE CONCAT(  '%/', r.region_id,  '/%' ) and p.active =1
WHERE r.parent_region_id =1
GROUP BY r.region_name, r.region_id, r.abbreviation, r.map_order
ORDER BY r.map_order ASC 
Ike Walker
that did the trick! thanks a ton.
toddm
any ideas on optimizing this? I'm a mysql newbie.. i've added indexes to the path column.. but didn't seem to do much. thanks!
toddm