2012-01-19 88 views
1

我有兩個表,message_threadsmessages。返回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 BYDISTINCT,但都沒有做到我想要的。我也不能使用WHERE子句來過濾我的數據,因爲我需要所有線程,而不管is_read標誌。

謝謝!

+0

你如何決定哪些MESSAGE_ID從每個線程組返回? –

+0

這裏還沒有足夠的東西來找出你想要的所有字段的正確調用。你對message_id和type列有什麼期望?你可能最終會遇到某種羣體,我懷疑是案例還是次級挑選,但根據你在這裏展示的內容我無法真正提供建議。 – Ilion

+0

我不確定,我認爲這是我的問題的一部分。理想情況下,message_id應該是最近未讀發件人的郵件標識,否則是其他任何郵件。 –

回答

2

有很多方法可以做到這一點。如果您希望查看線程中未讀郵件的數量,則可能需要加入內部查詢。

例子:

SELECT 
mt.id AS thread_id, 
mt.company_id, 
CASE WHEN m_c.m_unread IS NOT NULL THEN m_c.m_unread ELSE 0 END AS unread 
FROM message_threads AS mt 
LEFT JOIN 
( 
    SELECT 
    thread_id, 
    COUNT(*) AS m_unread 
    FROM messages 
    WHERE 
    is_read ='N' 
    GROUP BY 1 
)m_c 
ON mt.thread_id = m_c.thread_id 
+2

您可以通過使用'COALESCE(m_c.m_unread,0)' – Ilion

+0

來避免case語句。這和@ Ilion的評論正是我所需要的。 –