Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double LEFT JOIN

Tags:

I want to receive property name and units count and specails count. I have this query:

SELECT 
  `property`.`property_name`,
  COUNT(unit_id) AS `units_count`,
  COUNT(special_id) AS `specials_count` 
FROM `property`
  LEFT JOIN `property_unit` ON unit_property_id = property_id
  LEFT JOIN `property_special` ON special_property_id = property_id
WHERE (property_id = '1')
GROUP BY `property_id`
ORDER BY `property_name` ASC

But it is not working properly. If I have one of these left joins - it's ok, but if I have two, I get this result:

["property_name"] => string(11) "Rivers Edge"
["units_count"] => string(1) "2"
["specials_count"] => string(1) "2"

Specials count is 2 and units_count is 2, but units count is really '1'. How can I get correct counts for it?

P.S: for those who know Zend Framework:

$select->setIntegrityCheck(FALSE)
    ->from(
        'property',
        array(
            'property_name',
        )
    )
    ->joinLeft(
        'property_unit',
        'unit_property_id = property_id',
        array(
            'units_count' => 'COUNT(unit_id)'
        )
    )
    ->joinLeft(
        'property_special',
        'special_property_id = property_id',
        array(
            'specials_count' => 'COUNT(special_id)'
        )
    )
    ->group('property_id')
    ->order('property_name');