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。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。
有什么不对吗?
答案 0 :(得分:3)
您可以加入主查询Lecturer
和Class
并应用不同的内容,因此您可以使用少于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
。
您没有指定您正在使用的数据库。更典型的情况是,您可以将此信息放在FROM
或SELECT
条款中,这样您就可以看到学生人数:
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;