Query "all of" across many-to-many relation
7
votes
3
answers
15131
views
Imagine a setup of three tables, User, Group, and UserGroup, where UserGroup consists of simple a foreign key to each of User and Group tables.
User
----
id
name
Group
-----
id
name
UserGroup
---------
user_id
group_id
Now, I want to write a query selecting all users that are in all of some specified groups. e.g. Select * from users where the user is part of every one of "group1", "group2", and "group3".
With a Django ORM query, I'd do something like
users = (
User.objects
.filter(user_group__group_id=group1.id)
.filter(user_group__group_id=group2.id)
.filter(user_group__group_id=group2.id)
)
Which would produce a join for each call to
.filter
, e.g.
SELECT * FROM users
INNER JOIN user_group g1 ON g1.user_id = id
INNER JOIN user_group g2 ON g2.user_id = id
INNER JOIN user_group g3 ON g3.user_id = id
WHERE g1.group_id = %s
AND g2.group_id = %s
AND g3.group_id = %s
This becomes a bit hairy if I were to query a bigger set to match by.
So what is a better way to do this? If I were to ask for "any" rather that "all", if would be a simple matter of
SELECT * FROM users
INNER JOIN user_group g1 ON g1.user_id = id
WHERE g1.group_id in %s
But that is not what I need.
A small note: My specific environment is on Postgres, so no fancy MSSql thing will help me here. Preferably, the answer should be general enough to use in any SQL flavour.
Asked by Eldamir
(317 rep)
Apr 23, 2019, 01:01 PM
Last activity: Nov 4, 2022, 09:42 PM
Last activity: Nov 4, 2022, 09:42 PM