0

I have an elementary many-to-many relation in my Postgresql DB

Table - User

id name ...

Table - Chat

id name

Table - chatuser

id userId chatId

And I would like to get all chats (actually, there will be only one such chat), which will have only users, defined by their ids.

For example, I have user with id 1, user with id 2 and user with id 3. How can I get chats, which contain only these users, not less and not more. That means, that chats with only someone of these users will not be included in the result. Only chats which contain exactly these users

I understand, there`s got to be such question already, but I did not manage to find it.

1 Answer 1

0

Here is one method using group by and having:

select cu.chatid
from chatuser cu
group by cu.chatid
having sum(case when cu.userid not in (1, 2, 3) then 1 else 0 end) = 0;

This counts the number of users that are not in your list. The = 0 says that the chatId has none of them.

In Postgres, you can shorten this to:

select cu.chatid
from chatuser cu
group by cu.chatid
having sum( (cu.userid not in (1, 2, 3))::int) = 0;
Sign up to request clarification or add additional context in comments.

3 Comments

Let`s suppose we have only 2 users in query with ids 1 and 2 to make it easier to check. Then it works strange for case, when I have two chatuser instances like {userId: 1, chatId: 1} and {userId: 2, chatId: 2}. I would like the query to return nothing in that case, but yours returns both chats.
@Andrey . . . A chat with only one user meets the conditions specified in the question. If you have a different question, then ask it as another question.
Possibly, I was not accurate enough. Tried to change my question according to the requirements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.