消息系统查询以获取最后的消息,未读消息的数量和对话中的用户数组

Jor*_*anc 7 mysql sql messaging

我正在使用具有两个表的消息传递系统和另一个包含用户信息的表.
对话可以在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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我已经有一个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
Run Code Online (Sandbox Code Playgroud)

我现在想要添加到这个完美工作的查询返回的能力:

  • 每个会话的未读消息数(所有消息的数量date_creaded大于date_lastView登录用户的数量)
  • 一个数组,包含User_ID每个对话中的每个用户,并按照他们上次在对话中发布消息的时间排序.
  • 随着最后一个数组的同样的想法,但随着FirstNameLastName用户.

我尝试了一些事情,但我真的不成功,所以我现在要求SO社区提供宝贵的帮助.

所有这些只能显示登录用户参与的对话.

它有帮助,我创建了一个SQLFiddle

小智 3

用户对话中未读消息的数量(此处为用户#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
Run Code Online (Sandbox Code Playgroud)

按上次活动排序的对话参与者:

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
Run Code Online (Sandbox Code Playgroud)

第三个查询应该与第二个查询一样,只是在 上再加入一个表user_id,对吗?

  • 出于优化原因?我不确定这会更快,因为增加了复杂性(意味着数据库将更难优化其操作顺序)并且因为您想要的输出是如此异构。即,第一个(子)查询本质上是“每个对话的行”​​,第二个/第三个——“每个对话/用户的行”。 (2认同)