SQL统计所有行而不是统计单个行
我有一个从数据库中请求数据的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
这是我的messages_aura
表格布局。 它显示ID
, Status
和UserID
。
以上是上述声明的输出。
(以上屏幕截图的ID
参考下面的Poster
,以上屏幕截图的Status
参考下面的ID
)
声明应该给最底一行一个灵气计数1
,最上一行灵光计数2
。 怎么了?
你错过了GROUP BY
,所以它正在计算一切,而不是按某些列进行分组。
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)