2011-12-07 118 views
5

我想收到属性名称和单位数量和specails数量。我有这个查询:双左连接

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”。我如何得到正确的计数呢?

PS:对于那些谁知道Zend框架:

$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'); 
+0

property_unit和property_special表上的unit_id和special_id唯一键? –

+0

@Mark Ba​​nnister是 –

回答

9

试试这个:

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 

编辑:

你不应该始终使用使用不同 - 在这种情况下恰好是正确的选项。

select count(fieldname)返回fieldname不为空的次数; select count(distinct fieldname)返回字段名的不同值的数量。

在原始查询中,property_unit和property_special不会彼此连接,只能连接到属性 - 对于具有5个单位和7个特殊属性的单个属性,将返回35行;因此count(unit_id)count(special_id)就都返回35.自会有5个不同的UNIT_ID的价值观和7个不同special_id值(因为这些领域唯一标识的记录),count(distinct ...)返回正确的值在这种情况下。

+0

非常感谢,它的作品!但我不明白为什么我应该总是使用DISTINCT .. –

+0

@DmitryTeplyakov:看到更新的答案。 –

+0

非常感谢!这是很好的解释! –

1

你的SQL应该是这样的:

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

+0

同一查询。 unit_id和special_id是独一无二的 –