Consider the following simplified example:
CREATE TABLE groups ( gid INTEGER PRIMARY KEY, name VARCHAR(100) );
CREATE TABLE people ( pid INTEGER PRIMARY KEY );
CREATE TABLE people_groups (
gid INTEGER NOT NULL
CONSTRAINT fk_people_groups_group
REFERENCES groups(gid),
pid INTEGER NOT NULL
CONSTRAINT fk_people_groups_person
REFERENCES people(pid),
CONSTRAINT pk_people_groups PRIMARY KEY (gid, pid)
);
INSERT INTO people (pid) VALUES (1);
INSERT INTO groups (gid, name) VALUES (1, 'One');
INSERT INTO groups (gid, name) VALUES (2, 'Two');
INSERT INTO people_groups (gid, pid) VALUES (1,1);
INSERT INTO people_groups (gid, pid) VALUES (2,1);
SELECT gid, name FROM groups WHERE gid IN (
SELECT gid FROM people_groups WHERE pid = 1
);
This outputs:
1|One 2|Two
What is the correct JOIN for that last SELECT?
Note: This is equivalent to your
INstatement, because you specifically filter for only one person. If you filter for multiple persons, things are different. For example, assume that some person withpid=2is also in group 1 and you do the following SELECT:This would return group 1 twice (in contrast to your
INsolution, which would return each group only once). To solve this, you need to add theDISTINCTkeyword after theSELECTor addGROUP BY g.gid, g.nameat the very end of the SQL. You should keep that in mind if you use this answer as a general rule to convertINtoJOIN.