2012-06-09 40 views
7

我正在使用兩個表和另一個表與用戶信息的消息系統。
對話可以在2個或更多用戶之間進行。每個對話都有一個UID,每個用戶之間交換的消息都標有該對話UID。消息系統查詢以獲取最後的消息,未讀消息的數量和用戶在對話中的數組

下面是表:

conversation_list:此表的每一行的鏈接user_idconversation_id,它也包含了用戶最後一次查看的談話。

`id`     -> unique ID, autoincremented 
`user_id`   -> This contains the user associated with the conversation. 
`conversation_id` -> This contains the UID of the conversation 
`date_lastView`  -> This field has the time that the user viewed the conversation last 

conversation_messages:此表中的每一行包含一條消息

`id`     -> unique ID, autoincremented 
`user_id`   -> This contains the user that sent the message. 
`conversation_id` -> This contains the UID of the conversation 
`date_created`  -> This contains the time when the message was posted 
`message`   -> This contains the message 

users:此表中的每一行包含一個用戶

`User_ID`   -> UID of the user 
`FirstName`   -> This contains the first name of the user 
`LastName`   -> This contains the last name of the user 

我已經有一個SQL查詢來獲取每個對話的最後一條消息。那就是:

SELECT * 
FROM conversation_messages AS m 

JOIN 
    (SELECT mx.conversation_id, 
      MAX(mx.date_created) AS MaxTime 
    FROM conversation_messages AS mx 
    GROUP BY mx.conversation_id) AS mx ON m.conversation_id = mx.conversation_id 
AND m.date_created = mx.MaxTime 

JOIN 
    (SELECT mu.conversation_id 
    FROM conversation_list AS mu 
    WHERE mu.user_id = :USER_ID_CONNECTED 
    GROUP BY mu.conversation_id) AS mux ON m.conversation_id = mux.conversation_id 

JOIN conversation_list AS mu ON m.conversation_id = mu.conversation_id 

GROUP BY mu.conversation_id 
ORDER BY m.date_created DESC 

我現在想添加到這個完美的工作查詢返回的能力:

  • 未讀郵件的每個對話(數量與date_creaded更大的所有消息的計數那麼登錄用戶的date_lastView
  • 一個數組,包含每個對話中每個用戶的User_ID,並在他們上次在對話中發佈消息時進行排序。
  • 與最後一個數組相同的想法,但用戶的FirstNameLastName

我嘗試了一些東西,但我真的不成功,所以我現在要求SO社區提供寶貴的幫助。 。

這一切都只能顯示通話情況:登錄的用戶參與在

它有幫助,我在用戶的會話創建的未讀消息的SQLFiddle

+0

一個寫得很好的問題+1。 – Ben

+0

小提琴的另一個+1。 – JStead

回答

2

編號(這裏用戶#6):

SELECT l.conversation_id, count(*) 
FROM conversation_list l 
JOIN conversation_messages m ON m.conversation_id = l.conversation_id AND m.date_created > l.date_lastview 
WHERE l.user_id = 6 
GROUP BY l.conversation_id 

與會者交談通過最後一個活動下令:

SELECT conversation_id, user_id, max(date_created) as last_active 
FROM conversation_messages 
GROUP BY conversation_id, user_id 
ORDER BY conversation_id, last_active 

第三個查詢應該與第二個查詢一樣,只需加入user_id上的另一個表格,對不對?

+0

嗯,我知道如何做到這一點,但是我的大問題是在我的問題中使用的SQL代碼中實現這一點。 –

+0

我不明白... – doublep

+0

我想只將一個查詢中的所有信息都存入數據庫。 –

0

我加3個改進the query to fetch the unread messages

  • 如果last_view字段爲空,它會假設該用戶從未檢查他的郵件,因此所有的消息將是「未讀」
  • 確定爲新消息只是那些不是由用戶創建的消息。
  • 當有未讀郵件,計數將返回0
SELECT l.conversation_id, count(m.id) 
FROM conversation_list l 
LEFT JOIN conversation_messages m ON m.conversation_id = l.conversation_id AND (l.date_lastview IS NULL OR m.date_created > l.date_lastview) AND m.user_id != 6 
WHERE l.user_id = 6 
GROUP BY l.conversation_id