我有一个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
,顶行的灵气计数为{{1}}。怎么了?
答案 0 :(得分:3)
您错过了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)