如何使用UNION将字段与值相加?

时间:2016-05-14 20:06:46

标签: mysql sql

我希望仅对status之前的一个子查询计算字段1等于UNION的行:

SELECT sender, login, sex, avatar, status, 
    SUM(case when status = 1 AND receiver = 1 then 1 else 0 end) AS unread_messages 
FROM messages 
LEFT JOIN users 
ON users.idUser = messages.sender 
WHERE receiver = 1

它的工作正确,但是当我为第一次查询添加UNION时:

... UNION SELECT receiver, login, sex, avatar, status, idMessage 
FROM messages 
LEFT JOIN users 
ON users.idUser = messages.receiver 
WHERE sender = 1 
GROUP BY receiver, sender

它破坏了计数的结果。因此,对于receiver

,我只需要为第一次查询计数行数

我尝试添加其他条件:

case when (status = 1 and receiver = 1)

1 个答案:

答案 0 :(得分:-1)

您的第一个和第二个SELECT字段不同。

您必须在两者中添加字段:

首先选择:

SELECT sender, login, sex, avatar, status, null idMessage
       SUM(case when status = 1 AND receiver = 1
                then 1 else 0 end) AS unread_messages

第二次选择:

SELECT receiver, login, sex, avatar, status, idMessage, null unread_messages