I have a database as:
Student (ID, Name, Grade)
Likes (ID1, ID2)
Where ID1 and ID2 in last table are foreign key referenced student(ID)
Note: Liking isn't a mutual relation, eg its not necessary that if (123, 456) is in Likes table, then (456,123) is also in Likes table.
I have to write query for the following statement: "For every pair of students, who both like each other, return the name and grade of both students. Include each pair only once, with the two names in alphabetical order."
So far I have given the data in which ID1 and ID2 mutually like each other:
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);
Someone kindly help me how to avoid duplicate pairs.
Database is: (If someone needs it)
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);
and according to data entered:
DATA I GET
1689 Gabriel 1709 Cassandra
1709 Cassandra 1689 Gabriel
1501 Jessica 1934 Kyle
1934 Kyle 1501 Jessica
IDEAL DATA
1689 Gabriel 1709 Cassandra
1501 Jessica 1934 Kyle
Since the question is " how to avoid duplicate pairs. ":
You join 2 tables to get the ones where they both like each other, you will get 2 rows for each pair.
You can discard one by comparing against some distinct value. ID is a great candidate:
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
Try below query:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.