2015-05-15 19 views
2

我有這個疑問:如何重寫此MySQL查詢以返回計數?

SELECT accounts.id 
FROM accounts 
    LEFT JOIN account_properties ON account_properties.account_id = accounts.id 
GROUP BY accounts.id 
HAVING COUNT(account_properties.id) = 0 

它返回它的帳戶沒有任何帳戶屬性的所有帳戶ID的列表。我怎樣才能得到沒有財產的所有帳戶的數量?

SELECT COUNT(accounts.id) 
FROM accounts 
    LEFT JOIN account_properties ON account_properties.account_id = accounts.id 
GROUP BY accounts.id 
HAVING COUNT(account_properties.id) = 0 

這不起作用,只返回1的列表。

enter image description here

回答

3

您可能會發現這些查詢更快......假設ID是帳戶的唯一標識符。

對於IDS:

SELECT accounts.id 
    FROM accounts 
LEFT JOIN account_properties ON account_properties.account_id = accounts.id 
    WHERE account_properties.id IS NULL 

對於IDS的計數:

SELECT COUNT(*) 
    FROM accounts 
LEFT JOIN account_properties ON account_properties.account_id = accounts.id 
    WHERE account_properties.id IS NULL 
+0

謝謝。首先使用GROUP BY/HAVING檢索感覺錯誤的ID。這好多了。不知道有關檢查是否有任何列已加入的IS NULL技巧。 – Aich

+0

是的,這就是我的意思 –

+0

@Aich我的榮幸..這是相當普遍的。如果你需要,不要害怕用一個計數來包裝一個查詢。如果這是你正在與...正在接受答案。 – Arth

1
select count(*) from (SELECT accounts.id 
    FROM accounts 
    LEFT JOIN account_properties ON account_properties.account_id = accounts.id 
    WHERE exists account_properties.id 
    GROUP BY accounts.id) 
+0

我認爲用於HAVING的COUNT將始終爲1(除非帳戶擁有超過1個屬性)。 – Uueerdo

+0

是不是他如何過濾哪些記錄具有0的道具?或者你是否在說,即使它不= 0,它仍會回到1? –

+0

是的,「COUNT」確實只是計算行數,「LEFT JOIN」每個帳戶至少會有一行。而且他的查詢沒有返回他期望的結果。 – Uueerdo

1
SELECT `ap`.account_id IS NULL AS noProperties 
    , COUNT(DISTINCT `a`.id) AS accountCount 
FROM `accounts` AS `a` 
    LEFT JOIN `account_properties` AS `ap` N `ap`.account_id = `a`.id 
GROUP BY noProperties 
HAVING noProperties 
; 

本集團獲得使用和不使用性質賬戶的數量,和HAVING對結果進行過濾所以只有沒有財產賬戶的計數纔是最終結果。