Implementation of duplicate query and de duplicate of MySql data

Suppose there is a table user, and the fields are id – nick'u name – password – email – phone, as follows (please create a temporary table when deleting redundant records, otherwise an error will be reported):

1, Single field (nick'u name)

1. Find out all records with duplicate records

select * from user where nick_name in
     (select nick_name from user group by nick_name having count(nick_name)>1);

2. Find out the record with the largest id in each record group with duplicate records

select * from user where id in (select max(id) from user group by nick_name having count(nick_name)>1);

3. Find out the redundant records, not the records with the smallest id

select * from user where nick_name in

     (select nick_name from user group by nick_name having count(nick_name)>1)

and id not in 

     (select min(id) from user group by nick_name having count(nick_name)>1);

4. Delete redundant duplicate records and only keep the record with the smallest id

delete from user where nick_name in
     (select nick_name from

          (select nick_name from user group by nick_name having count(nick_name)>1) as tmp1)

and id not in 

      (select id from 

          (select min(id) from user group by nick_name having count(nick_name)>1) as tmp2);

2, Nick'u name, password

1. Find out all records with duplicate records

select * from user where (nick_name,password) in

     (select nick_name,password from user group by nick_name,password where having count(nick_name)>1);

2. Find out the record with the largest id in each record group with duplicate records

select * from user where id in

     (select max(id) from user group by nick_name,password where having count(nick_name)>1);

3. Find out the redundant record data in each duplicate record group, and do not find the one with the smallest id

select * from user where (nick_name,password) in

     (select nick_name,password from user group by nick_name,password having count(nick_name)>1)

and id not in

     (select min(id) from user group by nick_name,password having count(nick_name)>1);

4. Delete redundant duplicate records and only keep the record with the smallest id

delete from user where (nick_name,password) in

     (select nick_name,password from

          (select nick_name,password from user group by nick_name,password having count(nick_name)>1) as tmp1)

and id not in

     (select id from

          (select min(id) id from user group by nick_name,password having count(nick_name)>1) as tmp2);

Posted on Mon, 04 May 2020 18:01:54 -0700 by luv2sd