DISTINCT,GROUP BY 都有去重的效果,他们区别在哪呢?
建一个表demo_list
id | name |
1 | alan |
2 | betty |
3 | cat |
4 | dade |
5 | alan |
6 | betty |
现在查出id,name去重
GROUP BY
1 SELECT id
2 FROM demo_list
3 GROUP BY name;
结果:
id |
1 |
2 |
3 |
4 |
DISTINCT
1 SELECT id,COUNT(DISTINCT name)
2 FROM demo_list
3 GROUP BY name;
结果:
id |
COUNT(DISTINCT name)
|
1 | 1 |
2 | 1 |
3 | 1 |
4 | 1 |
两种方法的区别:
group by是按指定的列分组查询的,是一种聚合查询,很多时候是为了做统计用,
distinct 是查询出来以后再把重复的去掉
性能上 group 比 distinct 要好很多