distinct和group by

关键字 distinct和group by

mysql提供的distinct这个关键字过滤重复的记录,实际中我们往往用distinct来返回不重复字段的条数(count(distinct 需要去重的字段)),其原因是distinct只能返回他的目标字段,而无法返回其他字段;
第一种情况,使用Distinct关键字,可以对单列进行去重,如下图所示:

select distinct testname from test where isdelete= 0

distinct和group by
结果:对 testname 字段进行去重处理,符合预期期望,确实筛选掉了重复的字段值testname;

提示:

此时的使用和group by的使用效果是一样的;
第二种情况,使用Distinct关键字(在前),查询多列数据,

select distinct testname ,testtype from test where isdelete= 0

distinct和group by
结果:对 testname 字段进行去重处理,结果不符合预期期望,没有筛选掉重复的字段值testname,由于他次考虑了另一个字段testtype;

提示:

如果需要查出多个字段值的时候需要,同时只需要去掉一个字段的重复值的时候,使用distinct就不合适了,需要使用group by;

总结:

distinct testname,testtype 这样的mysql 会认为要过滤掉testname和testtype两个字段都重复的记录,如果sql这样写:select testtype,distinct testname from test ,这样mysql会报错,因为distinct必须放在要查询字段的开头。

所以一般distinct用来查询不重复记录的条数

如果要查询不重复的记录,有时候可以用group by :

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!