Method and code for deleting duplicate records in MYSQL (2) bitsCN.com
4 rows in set (0.00 sec)
Mysql> create temporary table tmp_wrap select * from users_groups group by uid having count (1)> 1 union all
Select * from users_groups group by uid having count (1) = 1;
Query OK, 7 rows affected (0.11 sec)
Records: 7 Duplicates: 0 Warnings: 0
Mysql> truncate table users_groups;
Query OK, 14 rows affected (0.03 sec)
Mysql> insert into users_groups select * from tmp_wrap;
Query OK, 7 rows affected (0.03 sec)
Records: 7 Duplicates: 0 Warnings: 0
Mysql> select * from users_groups;
Query result (7 records)
Id uid gid
1 11 502
2 107 502
3 100 503
4 110 501
5 112 501
6 104 502
9 102 501
Mysql> drop table tmp_wrap;
Query OK, 0 rows affected (0.05 sec)
2. there is also a very streamlined approach.
Find the duplicate and remove the smallest one.
Delete users_groups as a from users_groups as,
(
Select *, min (id) from users_groups group by uid having count (1)> 1
) As B
Where a. uid = B. uid and a. id> B. id;
(7 row (s) affected)
(0 MS taken)
Query result (7 records)
Id uid gid
1 11 502
2 107 502
3 100 503
4 110 501
5 112 501
6 104 502
9 102 501
3. let's take a look at the efficiency of the two methods.
Run the following SQL statement:
Create index f_uid on users_groups (uid );
Explain select * from users_groups group by uid having count (1)> 1 union all
Select * from users_groups group by uid having count (1) = 1;
Explain select * from users_groups as,
(
Select *, min (id) from users_groups group by uid having count (1)> 1
) As B
Where a. uid = B. uid and a. id> B. id;
Query result (3 records)
Id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY users_groups index (NULL) f_uid 4 (NULL) 14
2 UNION users_groups index (NULL) f_uid 4 (NULL) 14
(NULL) UNION RESULT ALL (NULL)
Query result (3 records)
Id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY ALL (NULL) 4
1 PRIMARY a ref PRIMARY, f_uid 4 B. uid 1 Using where
2 DERIVED users_groups index (NULL) f_uid 4 (NULL) 14
Obviously, the second one is less than the first scan function.
BitsCN.com