在一个别名中选择具有两个条件的计数

时间:2017-12-23 23:42:28

标签: mysql

我的sql表具有以下结构:

id, sender, recipient, content, date_sent, last_activity, sender_read, recipient read

这是个人信息。 sender行是发送消息的用户ID。收到回复后,sender_read变为1recipient也是如此。我需要计算用户拥有的未读消息总数。我试过这样的事情:

SELECT COUNT(CASE WHEN recipient = ? AND recipient_read = 0 THEN 1 END) as unread FROM pm 
UNION SELECT COUNT(CASE WHEN sender = ? AND sender_read = 0 THEN 1 END) as unread FROM pm

但它似乎不起作用。基本上我需要结合两个计数并返回一个别名。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

只需将2个条件组合成单个案例表达式:

SELECT COUNT(CASE WHEN recipient = ? AND recipient_read = 0 THEN 1
                  WHEN sender = ? AND sender_read = 0 THEN 1 
                  ELSE null
             END) as unread FROM pm 
WHERE recipient = ? OR sender = ?