在使用 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;
正文完