mysql千万级数据量查询出所有重复的记录
查询重复的字段需要创建索引,多个条件则创建组合索引,各个条件的索引都存在则不必须创建组合索引
有些情况直接使用GROUP BY HAVING则能直接解决;但是有些情况下查询缓慢,则需要使用下面其他的方法
以下是本人整理出来的查询重复数据的SQL,适用于千万级数据量的MYSQL数据库。
1.适用于整数类型的
SELECT DISTINCT UId FROM vehicle WHERE 1=1 GROUP BY UId HAVING(COUNT(UId))>1;
2.分组排序
SELECT UId FROM ( SELECT UId,LicenseNo,IF(@grp=a.UId,@rank:=@rank+1,@rank:=1) rank,@grp:=a.UId FROM (SELECT UId,LicenseNo FROM vehicle WHERE 1=1 ORDER BY UId) AS a,(SELECT @grp:=0,@rank:=0) AS b )AS t WHERE t.rank=2;
3.适用于字符串类型,包含中文
SELECT DISTINCT(LicenseNo) FROM vehicle a WHERE 1 = 1 AND ((SELECT COUNT(LicenseNo) FROM vehicle WHERE LicenseNo = a.LicenseNo) > 1) ;
4.适用于字符串类型,不包含中文
SELECT DISTINCT (a.CarVIN) FROM vehicle a LEFT JOIN vehicle b ON a.CarVIN=b.CarVIN WHERE 1=1 AND a.id<>b.Id;
转载 https://mp.weixin.qq.com/s/U5nZ0Ss_oJ3W1CgF3SvtBQ