SQL计算所有行而不是计算单个行

时间:2014-07-03 20:38:40

标签: mysql 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表格布局。它显示IDStatusUserID

以下是上述陈述的输出。

(上面屏幕截图中的ID指的是Poster下面的Status,上面屏幕截图中的ID指的是下面的1

该声明应该给最底行的灵气计数为2,顶行的灵气计数为{{1}}。怎么了?

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)