SQL 查询返回总行数而非个体行数计数
在执行 SQL 查询时,务必正确使用 COUNT(*) 等聚合函数,以免得到错误的结果。请考虑以下语句:
<code class="language-sql">SELECT `ID`, `To`, `Poster`, `Content`, `Time`, ifnull(`Aura`, 0) AS `Aura` 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) GROUP BY `ID`, `Poster` ORDER BY `Time` DESC LIMIT 10;</code>
此查询的目标是从 messages
和 messages_aura
表中查询数据,计算每个用户的 aura 消息出现次数。然而,问题出在 LEFT JOIN
子查询中,缺少 GROUP BY
子句。
问题: 如果没有 GROUP BY
子句,子查询将返回所有用户的 aura 消息总数,而不是计算每个用户的数量。结果,输出显示不正确的计数,因为它聚合了所有行,而不是按相关列分组。
解决方案: 要解决此问题,必须将 GROUP BY
子句添加到 LEFT JOIN
子查询中:
<code class="language-sql">LEFT JOIN ( SELECT `ID` AS `AuraID`, `Status` AS `AuraStatus`, COUNT(*) AS `Aura` FROM messages_aura GROUP BY AuraID, AuraStatus ) aura ON (var.Poster = aura.AuraID AND var.ID = aura.AuraStatus)</code>
通过添加 GROUP BY AuraID, AuraStatus
,子查询现在按这些列分组结果,确保每个用户的 aura 计数都是准确的。
以上是为什么我的 SQL COUNT(*) 返回总计而不是单个行计数?的详细内容。更多信息请关注PHP中文网其他相关文章!