我有一个数据库:
Student (ID, Name, Grade)
Likes (ID1, ID2)
Where ID1 and ID2 in last table are foreign key referenced student(ID)
注意:点赞不是相互关系,例如如果(123, 456) 在点赞表中,那么(456,123) 也不必在点赞表中。
我必须为以下语句编写查询:“对于彼此喜欢的每对学生,返回两个学生的姓名和年级。每对只包括一次,两个名字按字母顺序排列。”
到目前为止,我已经给出了 ID1 和 ID2 相互喜欢的数据:
SELECT s1.ID, s1.name, s2.ID, s2.name
FROM student s1, student s2, likes l
WHERE s1.ID = l.ID1 AND s2.ID = l.ID2
AND l.ID1 IN (SELECT ID2 FROM likes)
AND l.ID2 IN (SELECT ID1 FROM likes);
有人请帮助我如何避免重复对。
数据库是:(如果有人需要)
INSERT INTO `student` VALUES (1025,'John',12),(1101,'Haley',10),(1247,'Alexis',11),(1304,'Jordan',12),(1316,'Austin',11),(1381,'Tiffany',9),(1468,'Kris',10),(1501,'Jessica',11),(1510,'Jordan',9),(1641,'Brittany',10),(1661,'Logan',12),(1689,'Gabriel',9),(1709,'Cassandra',9),(1782,'Andrew',10),(1911,'Gabriel',11),(1934,'Kyle',12);
INSERT INTO `likes` VALUES (1689,1709),(1709,1689),(1782,1709),(1911,1247),(1247,1468),(1641,1468),(1316,1304),(1501,1934),(1934,1501),(1025,1101);
并根据输入的数据:
我得到的数据
1689 Gabriel 1709 Cassandra
1709 Cassandra 1689 Gabriel
1501 Jessica 1934 Kyle
1934 Kyle 1501 Jessica
理想数据
1689 Gabriel 1709 Cassandra
1501 Jessica 1934 Kyle