为什么有“有"时为什么有“哪里"

编程入门 行业动态 更新时间:2024-10-27 05:28:24
本文介绍了为什么有“有"时为什么有“哪里"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道已经讨论了很多,但是我的研究都无法说服我MySQL中'where'和'having'子句之间的区别.据我了解,我们可以使用'having'实现'where'子句可以完成的所有工作.例如. select * from users having username='admin'.那为什么需要'where'子句?在何处使用会产生性能差异吗?

I know this is much discussed, but none of my research could convince me the difference between 'where' and 'having' clauses in MySQL. From what I understand we can achieve everything that can be done with 'where' clause using 'having' . For eg. select * from users having username='admin'. Then why do you need 'where' clause? Does using where make any performance differences?

推荐答案

WHERE子句在聚合之前从源中过滤数据,而HAVING子句在应用GROUP BY之后过滤数据.通常,这意味着任何非聚合过滤器都可以出现在任一位置,但是如果您的查询中没有引用列,则只能在WHERE子句中对其进行过滤.

The WHERE clause filters data from the source before aggregates, whereas HAVING clause filters data after the GROUP BY has been applied. Generally this means any non-aggregate filter can appear in either place, but if you have a column that is not referenced in your query, you can only filter it in a WHERE clause.

例如,如果您有下表:

| ID | VALUE | -------------- | 1 | 15 | | 2 | 15 | | 3 | 20 | | 4 | 20 | | 5 | 25 | | 6 | 30 | | 7 | 40 |

假设您要应用以下查询:

Suppose you wanted to apply the following query:

select value, count(value) from Table1 group by value

但是您只想在ID > 2处包括行.如果将其放在HAVING子句中,则会收到 错误 ,因为ID列在汇总后不可用,因为它不在SELECT子句中.在这种情况下,您将需要使用WHERE子句:

But you only wanted to include rows where ID > 2. If you put that in a HAVING clause, you will get an error, because the ID column is not available post aggregate as it is not in the SELECT clause. In that case, you would be required to use a WHERE clause instead:

select value, count(value) from Table1 where id > 2 group by value

演示: www.sqlfiddle/#!2/f6741/16

更多推荐

为什么有“有"时为什么有“哪里"

本文发布于:2023-11-25 16:37:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630517.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!