distinct 和 group by 的区别

前言

我们在sql里面经常看到 distinctgroup by,那么两者到底有何区别呢?下面就来一探究竟。

来看官方描述

链接: Mysql distinct 传送门

其中有这么一段描述:

Generally speaking, the DISTINCT clause is a special case of the GROUP BY clause. The difference between DISTINCT clause and GROUP BY clause is that the GROUP BY clause sorts the result set whereas the DISTINCT clause does not.

总的来说,distinct 就是 group by 的一种特例, group by 对结果集做了排序,而 distinct 没有。

Notice that MySQL 8.0 removed the implicit sorting for the GROUP BY clause. Therefore, if you use MySQL 8.0+, you will find that the result set of the above query with the GROUP BY clause is not sorted.

要注意的是 MySQL 8.0 开始,移除掉了 group by 的排序,因此如果你用 MySQL 8.0 的话,得到的结果集是没有排序的。

总结

所以,如果我们的sql只查字段的话,类似:

SELECT DISTINCT
    state
FROM
    customers

VS

SELECT 
    state
FROM
    customers
GROUP BY state;

总的来说,MySQL8.0 以下,如果不加索引的话,还是 distinct 会快一些,因为它没有对结果集做排序。如果加索引的话,几乎就是一样了,因为索引就是有序的,你对一个字段加了索引之后,你会发现排序超级快,这也告诉了我们另外一个道理: 我们在开发过程中,要结合 sql 情况来合理的建立索引,并尽可能将排序字段添加至索引中。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值