我想接收属性名称,单位数和特殊数量。我有这个查询:
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
但是它不能正常工作。如果我有这些左连接之一-没关系,但是如果我有两个,则得到以下结果:
["property_name"] => string(11) "Rivers Edge"
["units_count"] => string(1) "2"
["specials_count"] => string(1) "2"
特价商品计数为2,units_count为2,但单位计数实际上为'1'。如何获得正确的计数?
附言:对于那些了解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');
最佳答案
试试这个:
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
编辑:
您不应该总是使用distinct-在这种情况下,它恰好是正确的选择。
select count(fieldname)
返回字段名不为null的次数; select count(distinct fieldname)
返回字段名的不同值的数量。在原始查询中,property_unit和property_special不相互连接,而仅与property连接-因此,对于具有5个单位和7个特殊字符的单个属性,将返回35行;否则,将返回35行。因此
count(unit_id)
和count(special_id)
都将返回35。由于将有5个不同的unit_id值和7个不同的special_id值(因为这些字段唯一地标识了它们的记录),因此count(distinct ...)
在这些情况下返回正确的值。关于sql - 双左联接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8416967/