Skip to content
Advertisement

Query for getting distinct pairs from a single column with an added constraint

How would I go about getting distinct pairs from a column with a constraint that a pair should not be repeated? So I have a query as such

SELECT DISTINCT s1.author_set_s_author_id,
         s2.author_set_s_author_id
FROM submission_record_author_set s1, submission_record_author_set s2
WHERE s1.author_set_s_author_id != s2.author_set_s_author_id;

This gets me all possible pairs from that column with a constraint that it cannot pair with it self but this can still happen: (1,2) and (2,1).

A pair should never be repeated in my case. So the pair of 1 and 2 should only appear once. Any suggestions on how I would add that constraint to my SQL query?

Advertisement

Answer

You can simply replace the != comparison in your WHERE clause with either < (to get (1,2) instead of (2,1)) or > (to get (2,1) instead of (1,2)):

SELECT DISTINCT s1.author_set_s_author_id,
                s2.author_set_s_author_id
FROM submission_record_author_set s1, submission_record_author_set s2
WHERE s1.author_set_s_author_id < s2.author_set_s_author_id;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement