当 Distinct 和 Group By 的表现不同时?

2024-04-16数据库问题
7

本文介绍了当 Distinct 和 Group By 的表现不同时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我知道在简单查询中,Distinct 和 Group By 的性能和执行计划几乎相同.

I know in simple queries the performance and execution plans of the Distinct and Group By are almost the same.

例如

SELECT Name FROM NamesTable GROUP BY Name
SELECT DISTINCT Name FROM NamesTable

但我在某些情况下读过他们的表现会有所不同,例如在子查询等中?

But I've read in some scenarios their performance would be different e.g. in subqueries, etc?

那么,您能否举一些例子或解释一些性能不同的场景?

So, could you make some examples or explain some scenarios where their performance are different?

非常感谢

推荐答案

如果在字段列表中包含计算值,您将看到执行计划中的差异.

If you include a calculated value in the field list you will see a difference in the execution plan.

select Value,
       getdate()
from YourTable
group by UnitID

select distinct
       Value,
       getdate()
from YourTable

group by 查询在计算标量值之前进行聚合.distinct 查询在聚合之前计算标量值.

The group by query aggregates before it computes the scalar value. The distinct query computes the scalar value before the aggregate.

这篇关于当 Distinct 和 Group By 的表现不同时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

按天分组的 SQL 查询
SQL query to group by day(按天分组的 SQL 查询)...
2024-04-16 数据库问题
77

SQL 子句“GROUP BY 1"是什么意思?意思是?
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)...
2024-04-16 数据库问题
62

MySQL groupwise MAX() 返回意外结果
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)...
2024-04-16 数据库问题
13

MySQL SELECT 按组最频繁
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)...
2024-04-16 数据库问题
16

在 Group By 查询中包含缺失的月份
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)...
2024-04-16 数据库问题
12

为什么 Mysql 的 Group By 和 Oracle 的 Group by 行为不同
Why Mysql#39;s Group By and Oracle#39;s Group by behaviours are different(为什么 Mysql 的 Group By 和 Oracle 的 Group by 行为不同)...
2024-04-16 数据库问题
13