Mini Database- Subquery返回的值超过1

时间:2017-03-11 22:46:15

标签: sql sql-server database sql-server-2014

SELECT DISTINCT L.LecturerName
FROM Lecturer L
WHERE 5 > = 
(   SELECT  E.StudentID
    FROM    Class C, Enrolled E
    WHERE   C.ClassName = E.ClassName
    AND     C.LecturerID = L.LecturerID)

错误消息如下: -

  

Msg 512,Level 16,State 1,Line 1   子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

有什么不对吗?

2 个答案:

答案 0 :(得分:3)

您可以加入主查询LecturerClass并应用不同的内容,因此您可以使用少于5名学生(使用子查询)限制您对Enrollment的查询

试试这个:

SELECT DISTINCT L.LecturerName
FROM Lecturer L
JOIN Class C
    ON L.LecturerID = C.LecturerID
WHERE
    (SELECT count(E.ClassName)
     FROM Enrollment E
     WHERE C.ClassName = E.ClassName
     AND C.LecturerID = L.LecturerID) < 5

答案 1 :(得分:3)

子查询中需要COUNT(*)。此外,从不FROM子句中使用逗号。 始终使用正确的JOIN语法。

SELECT DISTINCT L.LecturerName
FROM Lecturer L
WHERE 5 >= (SELECT COUNT(*)
            FROM Class C JOIN
                 Enrolled E
                 ON C.ClassName = E.ClassName
            WHERE C.LecturerID = L.LecturerID
           );

我猜测DISTINCT中不需要SELECT

您没有指定您正在使用的数据库。更典型的情况是,您可以将此信息放在FROMSELECT条款中,这样您就可以看到学生人数:

SELECT L.LecturerName, COUNT(*) as NumStudents
FROM Lecturer L JOIN
     Class C
     ON C.LecturerID = L.LecturerID JOIN
     Enrolled E
     ON C.ClassName = E.ClassName
GROUP BY L.LecturerName
HAVING COUNT(*) <= 5;