我希望仅对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)
答案 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