Home >Database >Mysql Tutorial >Mysql deletes duplicate data and keeps the smallest ID
Find and delete duplicate data on the Internet and keep the data with the smallest ID. The method is as follows:
DELETE FROM people WHERE peopleName IN ( SELECT peopleName FROM people GROUP BY peopleName HAVING count(peopleName) > 1 ) AND peopleId NOT IN ( SELECT min(peopleId) FROM people GROUP BY peopleName HAVING count(peopleName) > 1 )
When you use it yourself, an error message is displayed:
1 delete from tb where id in (SELECT max(id) from tb GROUP BY user HAVING count(user)>1)
[Err] 1093 - You can't specify target table 'XXX' for update in FROM clause
I don’t know what the cause is yet.
Then find a way to distribute the operations, first filter out the data with duplicate users, and then use max() to select the larger row:
SELECT max(id) from tb GROUP BY user HAVING count(user)>1
Then delete the redundant data one by one based on the obtained max(id)
1 delete from tb where id=xx
The above is the detailed content of Mysql deletes duplicate data and keeps the smallest ID. For more information, please follow other related articles on the PHP Chinese website!