双LEFT JOIN

Dmi*_*kov 7 sql zend-framework left-join

我想收到属性名称和单位数和指定数.我有这个问题:

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
Run Code Online (Sandbox Code Playgroud)

但它不能正常工作.如果我有其中一个左连接 - 没关系,但如果我有两个,我得到这个结果:

["property_name"] => string(11) "Rivers Edge"
["units_count"] => string(1) "2"
["specials_count"] => string(1) "2"
Run Code Online (Sandbox Code Playgroud)

特价计数为2,units_count为2,但单位计数实际为'1'.我怎样才能获得正确的计数?

PS:对于那些了解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');
Run Code Online (Sandbox Code Playgroud)

小智 13

试试这个:

SELECT 
  `property`.`property_name`,
  COUNT(distinct unit_id) AS `units_count`,
  COUNT(distinct 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
Run Code Online (Sandbox Code Playgroud)

编辑:

你不应该总是使用不同的 - 在这种情况下恰好是正确的选择.

select count(fieldname)返回fieldname不为null的次数; select count(distinct fieldname)返回fieldname的不同值的数量.

在原始查询中,property_unit和property_special不会相互连接,只会连接到属性 - 因此对于具有5个单位和7个特殊项的单个属性,将返回35行; 因此count(unit_id),count(special_id)将返回35.因为将有5个不同的unit_id值和7个不同的special_id值(因为这些字段唯一地标识其记录),count(distinct ...)所以在这些情况下返回正确的值.