简体   繁体   English

子查询以计数MySQL中的未读消息

[英]Sub-query to count unread messages in MySQL

I have a table messages having following look 我有一个表messages具有以下外观

+------------+-----------+---------+---------+------+
| message_id | sent_from | sent_to | message | seen |
+------------+-----------+---------+---------+------+
|            |           |         |         |      |
+------------+-----------+---------+---------+------+

message_id is primary key message_id是主键

sent_from and send_to are integer fields having user id's sent_fromsend_to是具有用户ID的整数字段

message is a text field message是文本字段

seen having "YES" or "NO" values. seen具有“是”或“否”值。

I am using this query to filter last conversation of user having user_id 5 我正在使用此查询过滤具有user_id 5的用户的最后一次对话

SELECT a.message_id, a.sent_from, a.sent_to, a.message, a.seen, users.username, users.user_image
FROM messages a
  INNER JOIN 
  (SELECT sent_from, max(message_id) AS maxid from messages GROUP BY sent_from, sent_to) AS b ON
  a.message_id = b.maxid
INNER JOIN users ON users.user_id = a.sent_from
WHERE a.sent_to = 5

The above query selecting data like this 上面的查询选择了这样的数据

+------------+-----------+---------+---------+------+----------+------------+
| message_id | sent_from | sent_to | message | seen | username | user_image |
+------------+-----------+---------+---------+------+----------+------------+
| 39         | 3         | 5       | hello   | YES  | ali786   | image1.jpg |
+------------+-----------+---------+---------+------+----------+------------+
| 40         | 2         | 5       | hi      | YES  | john123  | image2.jpg |
+------------+-----------+---------+---------+------+----------+------------+
| 48         | 1         | 5       | hello   | NO   | shahid7  | image3.jpg |
+------------+-----------+---------+---------+------+----------+------------+

I want to add a sub-query in above query to add a column unread_messages at last. 我想在上面的查询中添加一个子查询,以最后添加一列unread_messages which will count the all messages from messages table having seen status "NO" sent by sent_from user id and sent to sent_to` user id 这将计数从所有消息messages具有表seen状态的“否”发送由sent_from用户id和sent to sent_to`用户标识

You can utilize conditional aggregation using COUNT(CASE WHEN ...) in your inner subquery to get the count of unread messages as well: 您可以在内部子查询中使用COUNT(CASE WHEN ...)使用条件聚合来获取未读消息的计数:

SELECT a.message_id, a.sent_from, a.sent_to, a.message, a.seen, 
       users.username, users.user_image, 
       b.unread_messages 
FROM messages a
  INNER JOIN 
  (SELECT sent_from, 
          max(message_id) AS maxid,
          COUNT(CASE WHEN seen = 'NO' THEN 1 ELSE NULL END) AS unread_messages 
   FROM messages 
   GROUP BY sent_from, sent_to) AS b ON a.message_id = b.maxid
INNER JOIN users ON users.user_id = a.sent_from
WHERE a.sent_to = 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM