WHERE 和 HAVING 之间的语义差异是什么?

发布于 2024-10-04 15:32:47 字数 250 浏览 0 评论 0原文

让我们先把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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

猥︴琐丶欲为 2024-10-11 15:32:47

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 the GROUP BY is applied. (You can't put GROUP BY aside, HAVING is a clause reserved for use with GROUP BY - leaving out the GROUP 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 while HAVING cannot. (In super trivial un-grouped result sets you could theoretically use an index for HAVING, but I've never seen a query optimizer actually implemented in this way).

望笑 2024-10-11 15:32:47

MySQL 评估查询直至并包括 WHERE 子句,然后使用 HAVING 子句对其进行过滤。这就是为什么 HAVING 可以识别列别名,而 WHERE 却不能。

通过省略 GROUP BY 子句,我相信您只是告诉查询不要对任何结果进行分组。

MySQL evaluates the query up to and including the WHERE clause, then filters it with the HAVING clause. That's why HAVING can recognize column aliases, whereas WHERE can't.

By omitting the GROUP BY clause, I believe you simply tell the query not to group any of your results.

诺曦 2024-10-11 15:32:47

概括地说,WHERE 过滤进入查询的数据(数据库表),而 HAVING 过滤查询的输出。

WHERE 子句中的语句只能引用表(和其他外部数据源),而 HAVING 子句中的语句只能引用查询生成的数据。

Very broadly, WHERE filters the data going into the query (the DB tables), while HAVING 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 the HAVING clause can only refer to the data produced by the query.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文