2011-12-07 125 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是獨一無二的 –