问题描述
我有以下两个表:
1. Lecturers (LectID, Fname, Lname, degree).
2. Lecturers_Specialization (LectID, Expertise).
我想找到专业化程度最高的讲师.当我尝试此操作时,它不起作用:
I want to find the lecturer with the most Specialization.When I try this, it is not working:
SELECT
L.LectID,
Fname,
Lname
FROM Lecturers L,
Lecturers_Specialization S
WHERE L.LectID = S.LectID
AND COUNT(S.Expertise) >= ALL (SELECT
COUNT(Expertise)
FROM Lecturers_Specialization
GROUP BY LectID);
但是当我尝试这个时,它起作用了:
But when I try this, it works:
SELECT
L.LectID,
Fname,
Lname
FROM Lecturers L,
Lecturers_Specialization S
WHERE L.LectID = S.LectID
GROUP BY L.LectID,
Fname,
Lname
HAVING COUNT(S.Expertise) >= ALL (SELECT
COUNT(Expertise)
FROM Lecturers_Specialization
GROUP BY LectID);
是什么原因?谢谢.
推荐答案
WHERE
子句在单个行上引入了条件;HAVING
子句在 aggregations 上引入了条件,即选择的结果,其中单个结果,例如 count、average、min、max 或 sum,已经从 多行.您的查询需要第二种条件(即聚合条件),因此 HAVING
可以正常工作.
WHERE
clause introduces a condition on individual rows; HAVING
clause introduces a condition on aggregations, i.e. results of selection where a single result, such as count, average, min, max, or sum, has been produced from multiple rows. Your query calls for a second kind of condition (i.e. a condition on an aggregation) hence HAVING
works correctly.
根据经验,在GROUP BY
之前使用WHERE
,在GROUP BY
之后使用HAVING
.这是一个相当原始的规则,但在 90% 以上的情况下都是有用的.
As a rule of thumb, use WHERE
before GROUP BY
and HAVING
after GROUP BY
. It is a rather primitive rule, but it is useful in more than 90% of the cases.
在此过程中,您可能希望使用 ANSI 版本的连接重新编写查询:
While you're at it, you may want to re-write your query using ANSI version of the join:
SELECT L.LectID, Fname, Lname
FROM Lecturers L
JOIN Lecturers_Specialization S ON L.LectID=S.LectID
GROUP BY L.LectID, Fname, Lname
HAVING COUNT(S.Expertise)>=ALL
(SELECT COUNT(Expertise) FROM Lecturers_Specialization GROUP BY LectID)
这将消除用作theta 连接条件的WHERE
.
这篇关于SQL - HAVING 与 WHERE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!