Dani
Dani

Reputation: 21

Sub-query to count unread messages in MySQL

I have a table messages having following look

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

message_id is primary key

sent_from and send_to are integer fields having user id's

message is a text field

seen having "YES" or "NO" values.

I am using this query to filter last conversation of user having 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. which will count the all messages from messages table having seen status "NO" sent by sent_from user id and sent tosent_to` user id

Upvotes: 0

Views: 392

Answers (1)

Madhur Bhaiya
Madhur Bhaiya

Reputation: 28834

You can utilize conditional aggregation using COUNT(CASE WHEN ...) in your inner subquery to get the count of unread messages as well:

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

Upvotes: 1

Related Questions