Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query for all pairs of elements that are only in different groups

Tags:

sql

mysql

I have a table called Survey with a Group Column and a Subject Column

CREATE TABLE survey (
  `group` INT NOT NULL,
  `subject` VARCHAR(16) NOT NULL,
  UNIQUE INDEX (`group`, `subject`)
);

INSERT INTO survey 
  VALUES
  (1, 'sports'),
  (1, 'history'),
  (2, 'art'),
  (2, 'music'),
  (3, 'math'),
  (3, 'sports'),
  (3, 'science')
;

I am trying to figure out a query that will return all pairs of subjects that are not part of the same group. So from my above example, I would like to see these pairs returned in a table:

science - history  
science - art  
science - music  
history - math  
sports  - art  
sports  - music  
history - art  
history - music

Thus, the query shouldn't return:

sports - history  

as an example since they are both in Group 1.

Thanks so much.

like image 314
Paul Avatar asked Mar 06 '11 22:03

Paul


Video Answer


1 Answers

SELECT s1.subject,
       s2.subject
FROM   survey s1
       JOIN survey s2
         ON s1.subject < s2.subject
GROUP  BY s1.subject,
          s2.subject
HAVING COUNT(CASE
               WHEN s1.groupid = s2.groupid THEN 1
             END) = 0   
like image 149
Martin Smith Avatar answered Nov 02 '22 23:11

Martin Smith