我有一个名为Survey的表,其中包含一个Group Column和一个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'),'music'),(3,'math'),'science')
;
我试图找出一个查询,它将返回不属于同一组的所有主题对.所以从上面的例子中,我希望看到这些对在表中返回:
science - history
science - art
science - music
history - math
sports - art
sports - music
history - art
history - music
因此,查询不应返回:
sports - history
作为一个例子,因为他们都在第1组.
非常感谢.
最佳答案
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