查询这些表的最佳方式是什么

What is the best way to query these tables

我有 4 个 table, 我正在尝试获取属于 ID 为 1 的用户的所有聊天记录,我可以在下面的查询中执行此操作,但我不确定它的效率如何。

其次,我想通过获取聊天中的所有其他用户以及 ID 为 1 的用户来使此查询更复杂一些,但我不确定如何执行此操作。

select * from chat_users left join chats on chat_users.chat_id = chats.id left join users on chat_users.user_id = users.id where user_id = 1
  1. 用户 - id,用户名

  2. 聊天 - id,聊天名

  3. chat_users id, user_id, chat_id

  4. 帖子 - post、id、文本

例如

如果我们将聊天 table 想象为:

id : 1 | chatname : FirstChat

Chat_users 作为

id : 1 | user_id : 1 | chat_id : 1
id : 2 | user_id : 2 | chat_id : 1

用户为

id: 1 | username: firstUser
id: 2 | username: secondUser

我最终想以一个查询结束 returns 用户 1 参与的所有聊天以及他们聊天中其他用户的数据,但是我不确定我会怎么做?

这是一种表达查询的方法:

select c.*, u.*
from chat_users cu
inner join chats c on c.id = cu.chat_id
inner join users u on u.id = cu.user_id
where exists (
    select 1 from chat_users cu1 where cu1.chat_id = cu.chat_id and cu1.user_id = 1
)

也许您只想要一个聚合:

select chat_id,
       group_concat( case when cu.user_id <> 1 then user_id end) as other_users
from chat_users cu
group by chat_id
having sum( cu.user_id = 1 ) > 0;

这 returns 聊天 ID 和用户 -- 这正是您所要求的。如果你愿意,可以加入其他信息。