2016-03-16 122 views
0

我正在参加斯坦福大学的在线数据库课程,并被困在练习中。 Here is the database。现在的问题是:SQL查询选择仅匹配特定条件的所有行

Find names and grades of students who only have friends in the same grade.

这里是我的尝试:

/* 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 
); 

而且我得到这个错误:

Query failed to execute: near 'ALL': syntax error

我检查我的SQL与online syntax checker,并把它传递。我错过了什么?

+1

这是SQL Server吗?或者mysql?你没有指定一个DBMS ..我实际上用IN或类似的构造替换ALL。 – Leptonator

+0

什么是错误信息? – JassyJov

+0

@Lemonator正确。要小心,sql有不同的方言,所以如果你是在互联网或书籍上的例子,请确保你使用的是相同的dtb软件。 – Divisadero

回答

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. 
+0

我认为他在学习,所以他想使用'全部',即使它不是解决问题的最佳和最有效的方法。 – Divisadero

+3

我一直在做SQL超过25年,即使一次都没有使用过'ALL' – jarlh

+0

@Divisadero我将添加全部。我最初的例子的抱怨是子查询中的连接,这是一个PITA来读取和维护irl – AdrianBR

相关问题