我正在使用兩個表和另一個表與用戶信息的消息系統。
對話可以在2個或更多用戶之間進行。每個對話都有一個UID,每個用戶之間交換的消息都標有該對話UID。消息系統查詢以獲取最後的消息,未讀消息的數量和用戶在對話中的數組
下面是表:
conversation_list
:此表的每一行的鏈接user_id
和conversation_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
,並在他們上次在對話中發佈消息時進行排序。 - 與最後一個數組相同的想法,但用戶的
FirstName
和LastName
。
我嘗試了一些東西,但我真的不成功,所以我現在要求SO社區提供寶貴的幫助。 。
這一切都只能顯示通話情況:登錄的用戶參與在
它有幫助,我在用戶的會話創建的未讀消息的SQLFiddle
一個寫得很好的問題+1。 – Ben
小提琴的另一個+1。 – JStead