Wednesday 5 September 2018

MySQL Left Outer Join with Count of the attached table, Show all records

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!

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

0 comments:

Post a Comment