I have a question I don't know how to ask right, so I start with the SQL Statement (Postgres):
SELECT pc.person_id
FROM groups g
LEFT OUTER JOIN group_clubs gc ON (gc.group_id = g.id)
LEFT OUTER JOIN person_club pc ON (gc.club_id = pc.club_id)
WHERE g.id = 2
What I have:
A group, which has a criteria with club, a user has to be in.
This is split up into the groups
table, the group_clubs
table and the person_club
table
What I want: I want to get all persons, who are in ALL the clubs, connected to this group. What I get: I get all the persons, who are in at least one of the clubs.
I am stuck and got no idea, how to get the result, only I need to intersect the results, but I don't know how to do it now...?!?
EDIT: To explain what I am looking for, here is a statement which does the same:
SELECT pc.person_id
FROM person_club pc
WHERE pc.club_id IN (
SELECT gc.club_id
FROM group_clubs gc
WHERE gc.group_id = 2
);
What I want is:
SELECT pc.person_id
FROM person_club pc
WHERE pc.club_id IN ALL(
SELECT gc.club_id
FROM group_clubs gc
WHERE gc.group_id = 2
);
The person should be IN ALL of the group_clubs listed by this statement!
I got the answer thanks to a colleague:
SELECT pc.person_id
FROM person_club_data pc
INNER JOIN group_clubs gc ON (gc.club_id = pc.club_id)
WHERE gc.group_id = 2
GROUP BY pc.person_id
HAVING COUNT(pc.person_id) >= (
SELECT COUNT(gc.club_id)
FROM group_clubs gc2
WHERE gc2.group_id = 2
)
I select the persons, and the persons who occur exactly as often as group_clubs rows can be found for group 2 and who are connected to this group.