当进行数据的去重查询时,使用group by效率更高。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了当进行数据的去重查询时,使用group by效率更高。相关的知识,希望对你有一定的参考价值。

参考技术A 对某字段进行去重时,在该字段不加索引和加索引的比较

加了索引之后 distinct 比没加索引的 distinct 快了 107倍。

加了索引之后 group by 比没加索引的 group by 快了 43倍。

不管是加不加索引 group by 都比 distinct 快。因此使用的时候建议选 group by

mysql中去重 用group by优化distinct 用法

参考技术A 在使用 MySQL 时,有时需要查询出某个字段不重复的记录,这时可以使用mysql提供的distinct这个关键字来过滤重复的记录,但是实际中我们往往用distinct来返回不重复字段的条数(count(distinct id)),其原因是distinct只能返回他的目标字段,而无法返回其他字段,例如有如下表user:

用distinct来返回不重复的用户名:select distinct name from user;,结果为:

这样只把不重复的用户名查询出来了,但是用户的id,并没有被查询出来:select distinct name,id from user;,这样的结果为:

distinct name,id 这样的mysql 会认为要过滤掉name和id两个字段都重复的记录,如果sql这样写:select id,distinct name from user,这样mysql会报错,因为distinct必须放在要查询字段的开头。

所以一般distinct用来查询不重复记录的条数。

如果要查询不重复的记录,有时候可以用group by :

select id,name from user group by name;

以上是关于当进行数据的去重查询时,使用group by效率更高。的主要内容,如果未能解决你的问题,请参考以下文章

sqlserver 用distinct和group by哪个效率高

MySQL GROUP BY 语句

对单个字段的结果进行去重,用distinct执行效率快,还是用group by快

ClickHouse 实时数据去重查询argMax +group by

SQL中查询多个字段时,GROUP BY 要怎么使用?

group by 分组去重查询