我参加了斯坦福大学的在线数据库课程并且参与了练习。 Here is the database。问题是:
查找只有同一年级朋友的学生的姓名和成绩。
这是我的尝试:
/* Select all highschoolers and their grades... */
SELECT h1.name, h1.grade
FROM Highschooler h1
/* ...where their grades are equal to all their friends' grades */
WHERE h1.grade = ALL(
/* Select friends' grades */
SELECT h2.grade
FROM Highschooler h2
JOIN Friend f
ON f.ID1 = h1.ID
AND f.ID2 = h2.ID
);
我收到了这个错误:
查询无法执行:接近'全部':语法错误
我用online syntax checker检查了我的SQL,然后通过了。我错过了什么?
答案 0 :(得分:0)
为什么不保持简单和标准,运行任何sql风格?你可以只使用联接。
select name, grade
from Highschooler h1
inner join friends f
on f.id1=h1.id
inner join Highschooler h2
on h2.id=f.id2
group by 1,2
having
sum(case when h1.grade=h2.grade then 1 else 0 end) = count(*) -- nr of friends with same grade equals total nr of friends.