I have two tables, message_threads and messages. When returning a results set of message_threads, I’m performing a JOIN on the two tables to see whether any message from the sender (to the receiver) within that thread is unread.
Below is my SQL…
SELECT mt.id AS thread_id, m.id AS message_id,
m.is_read, m.from_type, mt.company_id
FROM message_threads AS mt
LEFT JOIN messages AS m
ON m.thread_id = mt.id;
…the full results set from a given query…
+-----------+------------+---------+-----------+------------+
| thread_id | message_id | is_read | from_type | company_id |
+-----------+------------+---------+-----------+------------+
| 1 | 1 | N | company | 1 |
| 1 | 9 | N | company | 1 |
| 1 | 19 | N | company | 1 |
| 2 | 2 | Y | coder | 1 |
| 2 | 3 | N | company | 1 |
| 2 | 6 | N | company | 1 |
| 2 | 8 | N | company | 1 |
| 3 | 4 | N | company | 1 |
| 6 | 13 | N | company | 1 |
| 6 | 14 | N | coder | 1 |
| 6 | 15 | N | company | 1 |
| 8 | 20 | N | company | 1 |
| 8 | 21 | N | coder | 1 |
| 4 | 5 | N | company | 2 |
| 4 | 7 | N | company | 2 |
| 4 | 22 | N | coder | 2 |
| 5 | 10 | N | company | 8 |
| 5 | 11 | N | coder | 8 |
| 5 | 12 | N | company | 8 |
| 7 | 16 | N | company | 18 |
| 7 | 17 | N | coder | 18 |
| 7 | 18 | N | company | 18 |
+-----------+------------+---------+-----------+------------+
…and the desired result set:
+-----------+------------+---------+-----------+------------+
| thread_id | message_id | is_read | from_type | company_id |
+-----------+------------+---------+-----------+------------+
| 1 | 19 | N | company | 1 |
| 2 | 2 | Y | coder | 1 |
| 3 | 4 | N | company | 1 |
| 6 | 14 | N | coder | 1 |
| 8 | 21 | N | coder | 1 |
| 4 | 22 | N | coder | 2 |
| 5 | 11 | N | coder | 8 |
| 7 | 17 | N | coder | 18 |
+-----------+------------+---------+-----------+------------+
How can I perform this query? I’ve tried GROUP BY and DISTINCT, and neither quite do what I want. I also can’t do this using a WHERE clause to filter my data, because I need all the threads regardless of the is_read flag.
Thanks!
There are a lot of ways of doing this. If your looking to see the number of unread messages from a thread you may want to join an inner query.
Example: