简体   繁体   中英

What is the best way to query these tables

I have 4 tables, I'm trying to get all the chats that belong to the user with the id of 1, I can do that shown in the query below however I'm unsure of how efficient it is.

Secondly, I want to make this query a bit more complex by also getting all the other users which are in the chats along with the user that has the id of 1 however I'm unsure how to do this.

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. Users - id, username

  2. Chats - id, chatname

  3. chat_users id, user_id, chat_id

  4. Posts - post, id, text

Eg

If we imagine chats table as:

id : 1 | chatname : FirstChat

Chat_users as

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

Users as

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

I eventually want to end up with a query that returns all the chats that user1 is involved in along with the data for the other users in them chats however I'm not sure how I would do that?

Here is one way to phrase the query:

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
)

Perhaps you just want an aggregation:

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;

This returns the chat id and the users -- which is what you are asking for. You can join in other information if you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM