SQL counting all rows instead of counting individu

2019-01-01 04:23发布

I have a SQL statement which requests data from the database.

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

Here is my messages_aura table layout. It shows ID, Status and UserID.

Here is the output from the above statement.

(The ID from the above screenshot refers to Poster below and the Status from the above screenshot refers to ID below)

The statement should give the bottom row a Aura count of 1 and the top row an Aura count of 2. What's wrong?

标签: mysql sql
1条回答
有味是清欢
2楼-- · 2019-01-01 04:42

You're missing GROUP BY, so it's counting everything instead of grouping by some columns.

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)
查看更多
登录 后发表回答