I'm using PostgreSQL and PgAdmin 4 and I'm working with MusicBrainz database. I need to find the couples of label that have never released a release in common, but that they both have released a release with a third label (the same label for both).
In the database there are these tables: label (id, name..) id is primary key. release_label (id, release, label) id is primary key and label foreign key.
I've tried with self join but it is not working:
SELECT l1.name as label_1 , l2.name as label_2
FROM release_label as r1 INNER JOIN label as l1 ON r1.label=l1.id, label as l2
INNER JOIN (release_label as r2 LEFT JOIN release_label as r3
ON r3.label=r2.label)ON r2.label=l2.id WHERE r1.release != r2.release
AND r1.label!= r3.label AND r1.release=r3.release
GROUP BY label_1,label_2 ORDER BY label_1,label_2
Thanks in advice.
This query gets pairs of labels that have never released anything in common:
Now, you want a third label that has released with both . . .
EDIT:
An alternative method might be simpler:
The
fromclause generates all candidate trips of labels. Theexistschecks the three conditions you want to check. This is the version that I would use, because I think the logic is much easier to follow.In either of these queries, you can (of course) use
select distincton the first two ids to just get the pairs you are looking for.