前言
我们在sql里面经常看到 distinct
和 group by
,那么两者到底有何区别呢?下面就来一探究竟。
来看官方描述
其中有这么一段描述:
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
情况来合理的建立索引,并尽可能将排序字段添加至索引中。