MYSQL在一条语句中进行多对多选择(聊天,最新消息,用户名)

桑吉特

我试图在一个语句中选择用户聊天列表,以及每个聊天的最新消息和消息发送者的姓名。

抽象的问题是:Ever chat可以有多个参与用户。消息发送给“聊天”,而不是特定用户。

这些是我想出的桌子

TABLE users (id, username)
TABLE chats (id)
TABLE messages (id, message, chat_id, user_id)

最后是聊天和参与者之间的多对多关系表

TABLE chats_users (chat_id,user_id)

我想列出某个用户参加的所有聊天,以及最新消息和发送者的用户名。我将如何在一份声明中说明呢?

我正在运行Mysql 5.0.9和php 7。

去世

该查询:

select max(m.id) id
from chats_users cu
inner join users u on cu.user_id = u.id
inner join messages m on m.chat_id = cu.chat_id
where cu.chat_id in (select chat_id from chats_users where user_id = ?) 
group by cu.chat_id

返回特定用户参与的所有聊天的最后一条消息
在此查询中使用它:

select m.chat_id, m.message, u.username
from messages m inner join users u
on u.id = m.user_id
where m.id in ( 
  select max(m.id) id
  from chats_users cu
  inner join users u on cu.user_id = u.id
  inner join messages m on m.chat_id = cu.chat_id
  where cu.chat_id in (select chat_id from chats_users where user_id = ?) 
  group by cu.chat_id
) 

获取这些消息的详细信息。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章