问题说明和数据库条件:数据库中有 3 个表(Highschooler、Friend和Likes),这里是数据库:
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
Friend
ID1 ID2
1510 1381
1510 1689
1689 1709
1381 1247
1709 1247
1689 1782
1782 1468
1782 1316
1782 1304
1468 1101
1468 1641
1101 1641
1247 1911
1247 1501
1911 1501
1501 1934
1316 1934
1934 1304
1304 1661
1661 1025
1381 1510
1689 1510
1709 1689
1247 1381
1247 1709
1782 1689
1468 1782
1316 1782
1304 1782
1101 1468
1641 1468
1641 1101
1911 1247
1501 1247
1501 1911
1934 1501
1934 1316
1304 1934
1661 1304
1025 1661
Likes
ID1 ID2
1689 1709
1709 1689
1782 1709
1911 1247
1247 1468
1641 1468
1316 1304
1501 1934
1934 1501
1025 1101
问题是:For every student who likes someone 2 or more grades younger than themselves, return that student's name and grade, and the name and grade of the student they like.
我的查询是:
select HS11.name,HS11.grade,HS22.name,HS22.grade from
( select ID1,ID2 from Likes where ID1 in
(
select HS1.ID from Highschooler HS1, Highschooler HS2
where HS1.ID<> HS2.ID and (HS1.grade - HS2.grade) >=2
)
and ID2 in
(
select HS2.ID from Highschooler HS1, Highschooler HS2
where HS1.ID<> HS2.ID and (HS1.grade - HS2.grade) >=2
)
) as G, Highschooler HS11, Highschooler HS22
where HS11.ID=G.ID1 and HS22.ID = G.ID2
我的查询输出是:
Alexis 11 Kris 10
John 12 Haley 10
预期输出为:
John 12 Haley 10
所以,我得到了额外的 1 行,这是不正确的。谁能指出我在这里做错了什么?