WHERE 和 HAVING 之间的语义差异是什么?
让我们先把GROUP BY
放在一边。在普通查询(没有GROUP BY
)中,语义差异是什么?为什么这个答案有效? (将别名放在 HAVING
子句中,而不是 WHERE
中)
Let's put GROUP BY
aside for a second. In normal queries (without GROUP BY
), what is the semantic difference? Why does this answer work? (put an alias in a HAVING
clause instead of WHERE
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
HAVING
对汇总行进行操作 -WHERE
在应用GROUP BY
之前对整个表进行操作。 (您不能将GROUP BY
放在一边,HAVING
是保留与GROUP BY
一起使用的子句 - 省略GROUP BY
不会改变幕后发生的隐式操作)。还需要注意的是,正因为如此,
WHERE
可以使用索引,而HAVING
则不能。 (在超级简单的未分组结果集中,理论上您可以使用HAVING
索引,但我从未见过实际以这种方式实现的查询优化器)。HAVING
operates on the summarized row -WHERE
is operating on the entire table before theGROUP BY
is applied. (You can't putGROUP BY
aside,HAVING
is a clause reserved for use withGROUP BY
- leaving out theGROUP BY
doesn't change the implicit action that is occurring behind the scenes).It's also important to note that because of this,
WHERE
can use an index whileHAVING
cannot. (In super trivial un-grouped result sets you could theoretically use an index forHAVING
, but I've never seen a query optimizer actually implemented in this way).MySQL 评估查询直至并包括
WHERE
子句,然后使用HAVING
子句对其进行过滤。这就是为什么HAVING
可以识别列别名,而WHERE
却不能。通过省略 GROUP BY 子句,我相信您只是告诉查询不要对任何结果进行分组。
MySQL evaluates the query up to and including the
WHERE
clause, then filters it with theHAVING
clause. That's whyHAVING
can recognize column aliases, whereasWHERE
can't.By omitting the
GROUP BY
clause, I believe you simply tell the query not to group any of your results.概括地说,
WHERE
过滤进入查询的数据(数据库表),而HAVING
过滤查询的输出。WHERE
子句中的语句只能引用表(和其他外部数据源),而HAVING
子句中的语句只能引用查询生成的数据。Very broadly,
WHERE
filters the data going into the query (the DB tables), whileHAVING
filters the output of the query.Statements in the
WHERE
clause can only refer to the tables (and other external data sources), while statements in theHAVING
clause can only refer to the data produced by the query.