SQL中WHERE和HAVING的区别
可能的重复:
SQL:HAVING和WHERE有什么区别?
我有看到了关于 WHERE
和 HAVING
的各种讨论。我仍然有一个问题:HAVING
仅在考虑聚合时使用,还是可以用更一般的术语使用:每当您在查询中创建或别名字段时? 我知道应该尽可能使用 WHERE
。
Possible Duplicate:
SQL: What's the difference between HAVING and WHERE?
I have seen various discussions on WHERE
and HAVING
. I still have a question: is HAVING
used only when considering aggregates, or can it be used in more general terms: whenever you have created or aliased a field in your query?
I know that WHERE
should always be used when possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
HAVING
指定搜索SELECT
语句中使用的内容。换句话说。
HAVING
适用于组。WHERE
适用于行。HAVING
specifies a search for something used in theSELECT
statement.In other words.
HAVING
applies to groups.WHERE
applies to rows.HAVING
仅适用于涉及与GROUP BY
子句结合使用的聚合的条件。例如。COUNT
、SUM
、AVG
、MAX
、MIN
。WHERE
适用于任何非聚合条件。它们甚至可以在同一查询中一起使用。例如。更新#1:
事实证明,
HAVING
有一种我不知道的非聚合用法。下面使用别名的查询仅适用于HAVING
关键字,不适用于WHERE
关键字。请参阅我在 MySQL 中的测试:更新#2:
我现在已经在 SQL Server 上测试了
HAVING
的新颖用法,但它不起作用。所以这可能是 MySQL 独有的功能。另外,@Denis 在评论中指出,此技巧仅在可以消除列/别名歧义的情况下才有效,并且仅适用于某些引擎。HAVING
is only for conditions involving aggregates used in conjunction with theGROUP BY
clause. eg.COUNT
,SUM
,AVG
,MAX
,MIN
.WHERE
is for any non-aggregage conditions. They can even be used together in the same query. eg.Update #1:
Turns out there is a non-aggregate usage of
HAVING
that I didn't know about. The query below which uses an alias only works with theHAVING
keyword, not theWHERE
keyword. See my test in MySQL:Update #2:
I've now tested the novel use of
HAVING
on SQL Server and it does not work. So this may be a MySQL-only feature. Also, @Denis pointed out in the comments that this trick only works if the column/alias can be disambiguated and it only works on some engines.WHERE
子句用于限制记录,也被查询优化器来确定要使用哪些索引和表。
拥有
是最终结果集上的“过滤器”,并在之后应用
GROUP BY
,所以sql不能用它来优化查询。WHERE
在提取时应用于每一行。HAVING
提取所有行,然后过滤结果。因此,
WHERE
不能用于聚合函数,因为它们需要提取完整的行集。The
WHERE
clause is used to restrict records, and is also used by thequery optimizer to determine which indexes and tables to use.
HAVING
is a "filter" on the final resultset, and is applied after
GROUP BY
, so sql cannot use it to optimize the query.WHERE
is applied for each row while extracting.HAVING
extracts all rows then filter the result.Thus
WHERE
cannot be used for aggregate functions, because they require the full rowset to be extracted.当您有一个
GROUP BY
子句并且您尝试根据分组字段之一进行过滤时,使用HAVING
;WHERE
用于否则进行过滤。例如。
HAVING
is used when you have aGROUP BY
clause and you are trying to filter based on one of the grouping fields;WHERE
is used for filtering otherwise.eg.