网站的两个用户之间的对话类型收件箱消息

时间:2018-09-08 08:24:37

标签: mysql sql database

我想在两个用户之间实现对话类型的收件箱消息,其中对话将在两个用户之间分组并显示在收件箱页面上,当单击对话时,总体聊天记录将显示在两个用户之间... 。 我有一个数据库架构,但未能对两个用户之间的对话进行分组。我需要查询才能实现这一点。谢谢 这是我的桌子。

1. 用户:

  • id
  • 用户名
  • 密码

2. 对话:

  • conversation_id
  • from_user
  • to_user

3. 消息:

  • message_id
  • conversation_id
  • user_id
  • message_text
  • 消息日期
  • 见过

因此,如果有人知道如何实现此查询,那么也请帮助我更改我的架构,谢谢

2 个答案:

答案 0 :(得分:0)

您可以使用如下所示的查询,通过对话获得当前用户的所有对话以及最后一条消息:

SELECT users.id,
       users.name,
       messages.conversation_id,
       messages.message_id,
       messages.message_text,
       messages.message_date,
       messages.seen
FROM
  (SELECT conversations.conversation_id,
          IF(conversations.from_user = <current_user_id>, conversations.to_user, conversations.from_user) AS interlocutor_id,
          max(messages.message_id) AS last_message_id
   FROM conversations
   LEFT JOIN messages ON conversations.conversation_id = messages.conversation_id
   WHERE convesations.from_id = <current_user_id>
     OR conversations.to_id = <current_user_id>
   GROUP BY conversations.conversation_id) AS t
LEFT JOIN users ON users.id = t.intercolutor_id
LEFT JOIN messages ON messages.message_id = t.last_message_id

如果您需要使用以下信息获取当前用户与上一次indox消息的所有对话:

SELECT users.id,
       users.name,
       messages.conversation_id,
       messages.message_id,
       messages.message_text,
       messages.message_date,
       messages.seen
FROM
  (SELECT conversations.conversation_id,
          IF(conversations.from_user = <current_user_id>, conversations.to_user, conversations.from_user) AS interlocutor_id,
          max(messages.message_id) AS last_message_id
   FROM conversations
   LEFT JOIN messages ON conversations.conversation_id = messages.conversation_id
   WHERE (convesations.from_id = <current_user_id>
          OR conversations.to_id = <current_user_id>)
     AND messages.user_id <> <current_user_id>
   GROUP BY conversations.conversation_id) AS t
LEFT JOIN users ON users.id = t.intercolutor_id
LEFT JOIN messages ON messages.message_id = t.last_message_id

但是我认为,如果您要重写数据库方案,并在“对话”表中添加最后一条消息的ID,那将是更好的方法。它将使查询更加优化

已更新:

如果需要获取与当前用户对话的所有用户的列表:

SELECT t.conversation_id,
       users.id,
       users.name
FROM
  (SELECT conversation_id,
          IF(from_user = <current_user_id>, to_user, from_user) AS interlocutor_id          
   FROM conversations   
   WHERE from_id = <current_user_id>
     OR to_id = <current_user_id>) AS t
LEFT JOIN users ON users.id = t.intercolutor_id

P.S。您必须将<current_user_id>替换为当前用户的实际标识符

答案 1 :(得分:0)

SELECT conversation FROM
        conversations

WHERE (conversations.from_user = <user parameter>
OR conversations.to_user = <user parameter>) 
AND conversations.from_user <> conversations.to_user