子查询不起作用,但手动输入

时间:2018-05-14 17:11:01

标签: sql subquery

当我尝试运行此查询时,我遇到“语法错误”。我的想法是在这两个类别中获得具有最大评估量的学生的姓名。

这失败了:

SELECT first_name,last_name
    FROM People
    WHERE ID IN  (
      SELECT ID_Student
            FROM Evaluations
            WHERE category IN ( 'Exam',
                                'Behaviour')
            GROUP BY ID_Student ORDER BY count(ID_Student) DESC ;
        );

虽然这很有效:

SELECT first_name,last_name 
    FROM People 
    WHERE ID IN  ( 42866836,53074038 );

我知道子查询可以自行运行,因为我可以将其删除并单独运行,并正确返回ID_ 学生列表。

有人可以建议吗?

3 个答案:

答案 0 :(得分:2)

尝试

SELECT first_name,last_name
    FROM People
    WHERE ID IN  (
      SELECT ID_Student
            FROM Evaluations
            WHERE category IN ( 'Exam',
                                'Behaviour')
            GROUP BY ID_Student ORDER BY count(ID_Student) DESC 
        );

DESC之后没有分号的语法错误。 ORDER BY在某种程度上也毫无意义。你可以删除它。使用GROUP BY,您可能希望减少子查询结果的基数以提高性能。但为此,您最好使用EXISTS和相关子查询重写它。

SELECT People.first_name,
       People.last_name
       FROM People
       WHERE EXISTS (SELECT *
                            FROM Evaluations
                            WHERE Evaluations.category IN ('Exam',
                                                           'Behaviour')
                                  AND Evaluations.ID_Student = People.ID);

无论如何

SELECT People.first_name,
       People.last_name,
       count(*)
       FROM People
            INNER JOIN Evaluations
                       ON Evaluations.Student_ID = People.ID
       WHERE Evaluations.category IN ('Exam',
                                      'Behaviour')
       GROUP BY People.first_name,
                People.last_name
       ORDER BY count(*) DESC;

似乎更符合您实际想要的内容。

答案 1 :(得分:2)

您想按评估次数订购人员吗?

试试这个:

with eval as (select id_student, COUNT(ID_Student) cnt  
    FROM Evaluations  
    WHERE category IN ( 'Exam',  
                        'Behaviour')  
    GROUP BY ID_Student)  
SELECT first_name,last_name  
    FROM People  
        inner join eval on people.id = eval.id_student  
        order by eval.cnt desc;  

否则,子查询中不需要组和顺序。

答案 2 :(得分:2)

标准 SQL Order by子句在subquery中无效,除非LIMIT中指定了TOP子句或subquery子句或者您可以直接使用FETCH FIRST

因此,您应该删除order by子句,或者您应该重新编写查询,与相关 subquery

一样
SELECT first_name,last_name
FROM People p
WHERE EXISTS (SELECT 1 
              FROM Evaluations 
              WHERE ID_Student = p.ID AND  
                    category IN ( 'Exam', 'Behaviour')
             );