sql数据库去重的几种情况
本文主要总结数据库去掉重复数据的方法
去掉重复数据的方法:
第一种:distinct
根据单个字段去重,能精确去重;
作用在多个字段时,只有当这几个字段的完全相同时,才能去重;
关键字distinct只能放在SQL语句中的第一个,才会起作用
上图举例说明:图中student_name 为 test的同学有两位,不同的是班级

首先,单个字段 -》用distinct对student_name 进行筛选,单个字段查询的话,可以看到已经将一个重复的test学生记录去掉了

应用在多个字段时,可以看到此时两个同名的test,都被查出来;应用在多个字段时,只有当多个字段重复才会去重

一般用来返回不重复的记录条数,返回不重复的条数(去掉test重复的,就剩下6条)

第二种:group by + count + min 去掉重复数据
没有加group by之前,有两条班级名称一样的数据

加上group by 后,会将重复的数据去掉了

count + group +min:去掉重复数据
首先根据查出重复的数据
然后再加上id不在查询结果里面的,去掉重复数据
SELECT * from tb_class where classname in (SELECT classname from tb_class GROUP BY classname HAVING COUNT(classname)>1)
and id NOT in (SELECT min(id) from tb_class GROUP BY classname HAVING count(classname)>1)

第三种:min、max(这种方法在第二种中已经用到了)