mysql 去重的两种方式

1.distinct一般用于获取不重复字段的条数

使用原则:

1)distinct必须放在要查询字段的开头,不能放在查询字段的中间或者后面

  select distinct name from user; 获取不重名的name 记录

  select id, distinct name from user; 这种写法是错误的,distinct只能写在所有查询字段的前面

2)distinct 对后面所有的字段均起作用,即去重是查询的所有字段完全重复的数据,而不是只对 distinct后面连接的单个字段重复的数据。

  select distinct name,id from user;获取id与name都不重复的记录

  注意点:distinct只能返回它的目标字段,无法返回其他字段

2.group by

select 字段 from user group by name;其中查询字段必须是group by后的字段或者一些聚合函数,,在某些情况下,查询字段中有其他字段也不会报错,但是容易混淆数据,不建议使用。

猜你喜欢

转载自www.cnblogs.com/mianbaoshu/p/13367942.html