*SQL COUNT() 錯誤聚合行:常見陷阱**
SQL 查詢中的一個常見挑戰涉及 COUNT(*)
聚合函數意外地計算所有行而不是執行預期的分組。 這通常源自於 GROUP BY
子句的錯誤放置或遺漏。
讓我們檢查一個有問題的查詢及其解決方案:
原始查詢旨在根據“Aura”狀態對行進行計數,並按“Poster”和“ID”分組:
<code class="language-sql">SELECT `ID`, `To`, `Poster`, `Content`, `Time`, ifnull(`Aura`,0) as `Aura` FROM ( SELECT * FROM ( SELECT DISTINCT * FROM messages m INNER JOIN ( SELECT Friend2 as Friend FROM friends WHERE Friend1 = '1' UNION ALL SELECT Friend1 as Friend FROM friends WHERE Friend2 = '1' ) friends ON m.Poster = friends.`Friend` UNION ALL SELECT DISTINCT *, '1' FROM messages where `Poster`='1' ) var LEFT JOIN ( select `ID` as `AuraID`, `Status` as `AuraStatus`, count(*) as `Aura` from messages_aura ) aura ON (var.Poster = aura.AuraID AND var.ID = aura.AuraStatus) ) final GROUP BY `ID`, `Poster` ORDER BY `Time` DESC LIMIT 10</code>
未達到預期結果,即每個「海報」和「ID」組合的「Aura」出現次數(例如,ID 1、海報 2 具有 2 個 Aura 實例)。 子查詢中的 COUNT(*)
函數錯誤地聚合了 messages_aura
.
解:正確分組GROUP BY
問題在於與 GROUP BY
連接的子查詢中缺少 messages_aura
子句。更正後的查詢是:
<code class="language-sql">SELECT `ID`, `To`, `Poster`, `Content`, `Time`, ifnull(`Aura`,0) as `Aura` FROM ( SELECT * FROM ( SELECT DISTINCT * FROM messages m INNER JOIN ( SELECT Friend2 as Friend FROM friends WHERE Friend1 = '1' UNION ALL SELECT Friend1 as Friend FROM friends WHERE Friend2 = '1' ) friends ON m.Poster = friends.`Friend` UNION ALL SELECT DISTINCT *, '1' FROM messages where `Poster`='1' ) var LEFT JOIN ( select `ID` as `AuraID`, `Status` as `AuraStatus`, count(*) as `Aura` from messages_aura GROUP BY AuraID, AuraStatus -- The crucial addition ) aura ON (var.Poster = aura.AuraID AND var.ID = aura.AuraStatus) ) final GROUP BY `ID`, `Poster` ORDER BY `Time` DESC LIMIT 10</code>
透過將 GROUP BY AuraID, AuraStatus
加到內部 SELECT
語句,COUNT(*)
函數現在可以正確計算 AuraID
和 AuraStatus
的每個唯一組合的行數,從而產生所需的分組結果。 這可確保 Aura
在行級別準確計數。 然後,外部 GROUP BY
子句根據 ID
和 Poster
進一步聚合結果。
以上是為什麼我的 SQL COUNT(*) 聚合所有行而不是按 ID 和海報分組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!