K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

Stuck with a SQL Query

Problem Specification and Database Condition: There are 3 tables (Highschooler, Friend and Likes) in the database and Here is the database :

Highschooler
ID  name    grade
1510    Jordan  9
1689    Gabriel 9
1381    Tiffany 9
1709    Cassandra   9
1101    Haley   10
1782    Andrew  10
1468    Kris    10
1641    Brittany    10
1247    Alexis  11
1316    Austin  11
1911    Gabriel 11
1501    Jessica 11
1304    Jordan  12
1025    John    12
1934    Kyle    12
1661    Logan   12

Likes
ID1 ID2
1689    1709
1709    1689
1782    1709
1911    1247
1247    1468
1641    1468
1316    1304
1501    1934
1934    1501
1025    1101

Question is : 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.

My query is :

select  H1.name,H1.grade,H2.name,H2.grade from 
(select ID1,ID2 from Likes 
where ID1 in (select ID2 from Likes) and
ID2 in (select ID1 from Likes)) as G JOIN Highschooler H1 JOIN Highschooler H2
where H1.ID=G.ID1 and H2.ID=G.ID2 order by H1.name,H2.name

My query's output is :

Cassandra 9   Gabriel  9
Gabriel   9  Cassandra 9
Jessica  11  Kyle   12
Kyle     12  Jessica 11

Expected output is:

Cassandra 9   Gabriel  9
Jessica  11   Kyle  12

I am not being able to remove one pair. How can I do that in SQlite?

Upvotes: 0

Views: 579

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270391

The simplest thing to do is to expand your final where clause to include:

where h1.name < h2.name

This will prevent the doubling of each pair in the output.

Upvotes: 4

Related Questions