我有兩個表,message_threads
和messages
。返回message_threads
的結果集時,我在兩個表上執行JOIN
以查看該線程中發件人(到接收方)的消息是否爲未讀取的任何消息。從消息線程獲取嵌套的未讀消息
下面是我的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;
...從給定的查詢中設置的全部結果...
+-----------+------------+---------+-----------+------------+
| 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 |
+-----------+------------+---------+-----------+------------+
...和期望的結果集:
+-----------+------------+---------+-----------+------------+
| 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 |
+-----------+------------+---------+-----------+------------+
如何執行此查詢?我已經嘗試過GROUP BY
和DISTINCT
,但都沒有做到我想要的。我也不能使用WHERE
子句來過濾我的數據,因爲我需要所有線程,而不管is_read
標誌。
謝謝!
你如何決定哪些MESSAGE_ID從每個線程組返回? –
這裏還沒有足夠的東西來找出你想要的所有字段的正確調用。你對message_id和type列有什麼期望?你可能最終會遇到某種羣體,我懷疑是案例還是次級挑選,但根據你在這裏展示的內容我無法真正提供建議。 – Ilion
我不確定,我認爲這是我的問題的一部分。理想情況下,message_id應該是最近未讀發件人的郵件標識,否則是其他任何郵件。 –