2017-08-01 58 views
1

我一直在研究PHP消息傳遞系統,並且我想實現訪問特定對話/線程的兩種方法。根據收件人從數據庫中選擇對話

第一個問題是查詢會話的ID(message/{numeric ID}),這非常簡單直接。它也是查詢羣組消息的唯一方法。

該部分的方法是查詢個人「1對1」消息線程(message/{alphanumeric user ID})。我將列出下面使用的三張表。

conversations

id | locked | timestamp 

timestamp表示在會話進行排序時具有較少的查詢起見最後一個消息的時間。

participants

id | conversation | member | timestamp 

conversation是國外ID鍵從conversationsmember是表members外鍵和timestamp在談話的「看到」的功能目的用戶的最後一項活動。

messages

id | member | conversation | message | timestamp 

列是不言自明這裏。

現在,我想取得對話的ID,我只根據成員ID將人員A和人員B作爲參與者。

我已經考慮了幾個小時,沒有想到優雅的解決方案。

+0

只有A和B.所以應該沒有其他人,對嗎? – iXCray

+0

確實,這是正確的 - 只有A和B,沒有其他人。 –

+0

但結果可能不止一次與這些標準進行對話。你想要所有的還是最新的? – steven

回答

1
SELECT c.id, c.timestamp 
FROM conversations c 
RIGHT JOIN participants p_a ON (p_a.conversation=c.id) 
RIGHT JOIN participants p_b ON (p_b.conversation=c.id) 
WHERE 
    p_a.member='A-ID' AND 
    p_b.member='B-ID' 
GROUP BY c.id 
HAVING count(*)=1 
ORDER BY c.timestamp DESC 

在參與者的1M記錄和對話中的400K記錄上花費0,012秒+網絡。

conversations.idPKparticipants.conversationFKconversations.id相連,participants.memberKEYconversations.timestampKEY

+1

爲什麼最大c.timestamp如果你通過c.id分組?這個組只能有一個時間戳。 – steven

+0

你說得對。更正 – iXCray

+0

優秀和優雅。非常感謝。 –

相關問題