我的sql表具有以下结构:
id, sender, recipient, content, date_sent, last_activity, sender_read, recipient read
这是个人信息。 sender
行是发送消息的用户ID。收到回复后,sender_read
变为1
,recipient
也是如此。我需要计算用户拥有的未读消息总数。我试过这样的事情:
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
但它似乎不起作用。基本上我需要结合两个计数并返回一个别名。我怎么能这样做?
答案 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 = ?