我有一个数据库:
Student (ID, Name, Grade)
Likes (ID1, ID2)
Where ID1 and ID2 in last table are foreign key referenced student(ID)
注意:喜欢不是一个相互关系,例如,如果(123,456)在Likes表中,那么(456,123)也在Likes表中是不必要的。
我必须为以下语句编写查询: “对于彼此喜欢的每一对学生,都要返回两个学生的姓名和成绩。每个学生只包括一次,两个名字按字母顺序排列。”
到目前为止,我已经给出了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
答案 0 :(得分:0)
因为问题是" 如何避免重复对。":
你加入2个表来获得他们俩彼此喜欢的表,每对你会得到2行。
您可以通过比较某些不同的值来丢弃一个。身份证是一个很好的候选人:
select * -- put fields here
from likes li
join likes li2 on li2.ID1 = li.ID2 and li2.ID2 = li.ID1
-- join 2 students here
where li.ID1 < li.ID2
答案 1 :(得分:0)
尝试以下查询:
SELECT L1.*
FROM `likes` l1
LEFT JOIN `likes` l2 ON l1.id1 = l2.id2 AND l1.id2 = l2.id1
WHERE l2.id2 IS NOT NULL
GROUP BY l1.id1 - l1.id2
HAVING l1.id1 - l1.id2 < 0