我正在开发一个包含两个表和另一个包含用户信息的表的消息传递系统。
对话可以在 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
andLastName
相同。
我尝试了一些事情,但我真的不成功,所以我现在请求 SO 社区提供宝贵的帮助。
所有这些只能显示登录用户参与的对话。
它有帮助,我创建了一个SQLFiddle