Note: Using Postgres
I tried for hours and read many posts but still can not figure out how to make this query.
I have two tables
chat table
id | is_group_chat |
---|---|
1 | false |
2 | false |
user_chat table (linked with user table)
chat_id | user_id |
---|---|
1 | 1 |
1 | 2 |
2 | 1 |
2 | 3 |
3 | 4 |
3 | 2 |
I need to select chat which is between two user only.
I have achieved this
select c.id as c_id, c.chat_name as chat_name, c.created_at as created_at
from chats c
left join user_chats uc on uc.chat_id = c.id
where c.is_group_chat = false
and uc.user_id = '39438219-1488-4e6f-820a-2ba16ba12e01'
intersect
select c.id as c_id, c.chat_name as chat_name, c.created_at as created_at
from chats c
left join user_chats uc on uc.chat_id = c.id
where c.is_group_chat = false
and uc.user_id = '16c1beb9-687a-45b3-8d2b-88c71a681168';
As you can see I needed to write almost same query two times is there any better way to do this.
Thanks in advance.
3
Answers
You could simply join the table, group the rows by the chat id, and then count them.
If you want to include chats that involved other users then just remove
count()
filter:If you possibly need to check more than two user ids (or if you just want to use this version with two ids):
Based on your sample query, you appear to be only interested in specific users. This is based on that appearance.
Use
HAVING
clause. Also, since you want to query user ids, then you INNER JOIN (not left join) to user_chat.View on DB Fiddle