私人消息系統顯示連接的用戶消息。php mysql連接發送和接收消息
•用戶發送和接收的分組在一起的消息通過time_sent
有序•每個消息標籤將會顯示發送者/接收者的姓名,消息和time_sent
•關於如何提高查詢速度(例如索引等任何提示。)?
MESSAGES TABLE
--------------
id sender receiver time_sent message opened recipientDelete senderDelete
Users Table
-----------
id first_name last_name
我嘗試:
$userid = logged in user
$query="SELECT MAX(id), sender, receiver, MIN(time_sent), message, opened
FROM messages
WHERE (receiver='$userid' AND recipientDelete='0')
OR (sender='$userid' AND senderDelete='0')
GROUP BY receiver,sender
ORDER BY time_sent DESC LIMIT 8";
RESULT /問題:
如果登錄用戶(ID = 3)從兩個用戶接收消息(ID = 1和ID = 2)這個查詢將返回從用戶發送1和2
第二次嘗試的消息:
$query="SELECT MAX(id), sender, receiver, MIN(time_sent), message, opened
FROM (SELECT
CASE WHEN sender = '$userid' THEN receiver ELSE sender END
MIN(time_sent)
FROM messages
WHERE sender = '$userid' OR receiver = '$userid'
GROUP BY CASE WHEN sender = '$userid' THEN receiver ELSE sender END)
ORDER BY time_sent DESC
LIMIT 8";
返回錯誤。
Jason,錯誤是什麼? – ajreal
第一個查詢將錯誤消息分組在一起。例如,如果您(jason =用戶1)正在查看您的收件箱,則查詢會將您(用戶1)作爲發件人或收件人的任何其他用戶(2,3,4等)分組。因此,當用戶1-2和1-3之間發送的消息應該是2個獨立的消息時,它們將作爲一條消息組合在一起。 – Bourne