Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于统计MySQL中未读邮件的子查询_Mysql_Sql - Fatal编程技术网

用于统计MySQL中未读邮件的子查询

用于统计MySQL中未读邮件的子查询,mysql,sql,Mysql,Sql,我有一张有如下外观的表格 +------------+-----------+---------+---------+------+ | message_id | sent_from | sent_to | message | seen | +------------+-----------+---------+---------+------+ | | | | | | +------------+-------

我有一张有如下外观的表格

+------------+-----------+---------+---------+------+
| message_id | sent_from | sent_to | message | seen |
+------------+-----------+---------+---------+------+
|            |           |         |         |      |
+------------+-----------+---------+---------+------+
消息id是主键

sent_from和send_to是具有用户id的整数字段

消息是一个文本字段

可以看到有“是”或“否”值

我使用此查询筛选用户id为5的用户的最后一次对话

上面的查询选择如下数据

+------------+-----------+---------+---------+------+----------+------------+
| 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 |
+------------+-----------+---------+---------+------+----------+------------+

我想在上面的查询中添加一个子查询,最后添加一列未读消息。这将统计messages表中看到状态NO sent by sent_from user id和sent to sent_to`user id的所有消息。当。。。在内部子查询中获取未读邮件的计数:

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

对于上面给出的示例数据,新列实际上是什么样子的?新列将出现在用户_图像之后,并对看到值NO的消息进行计数
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