简体   繁体   English

有子句与子查询

[英]Having clause vs subquery

I could write a query using an aggregate function in two ways: 我可以用两种方式使用聚合函数编写查询:

select team, count(min) as min_count
from table
group by team
having count(min) > 500

or 要么

select * 
from (
    select team, count(min) as min_count
    from table
    group by team
) as A
where A.min_count > 500

Are there any performance benefits to either approach or are they functionally the same thing? 这两种方法是否有任何性能优势,或者它们在功能上是否相同?

The two versions are functionally the same. 这两个版本在功能上是相同的。 Well, the second is syntactically incorrect, but I assume you mean: 好吧,第二个在语法上是不正确的,但我认为你的意思是:

select * 
from (
    select team, count(min) as count
    from table
    group by team
) t
where count > 500

(You need the alias on the calculation and several leading databases require an alias on a subquery in a FROM clause.) (您需要计算别名,并且几个主要数据库需要FROM子句中子查询的别名。)

Being functionally equivalent does not mean that they are necessarily optimized the same way. 在功能上等同并不意味着它们必须以相同的方式进行优化。 There are often multiple ways to write a query that are functionally equivalent. 通常有多种方法来编写功能相同的查询。 However, the specific database engine/optimizer can choose (and often does choose) different optimization paths. 但是,特定的数据库引擎/优化器可以选择(并且通常会选择)不同的优化路径。

In this case, the query is so simple that it is hard to think of multiple optimization paths. 在这种情况下,查询非常简单,很难想到多个优化路径。 For both versions, the engine basically has to aggregate teh query and then test the second column for the filter. 对于这两个版本,引擎基本上必须聚合查询,然后测试第二列的过滤器。 I personally cannot see many variations on this theme. 我个人看不到这个主题的很多变化。 Any decent SQL engine should use indexes, if appropriate, in either both cases or neither. 任何体面的SQL引擎都应该使用索引(如果适用),无论是两种情况还是两种情况。

So, the anwer to this specific question is that in any reasonable database, these should result in the same execution plan (ie, in the use of indexes, the user of parallelism, and the choice of aggregation algorithm). 因此,对这个特定问题的回答是,在任何合理的数据库中,这些都应该导致相同的执行计划(即,使用索引,并行用户和聚合算法的选择)。 However, being functionally equivalent does not mean that a given database engine is going to produce the same exeuction plan. 但是,在功能上等同并不意味着给定的数据库引擎将产生相同的执行计划。 So, the general answer is "no". 所以,一般的答案是“不”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM