Deleting Duplicate Records in MySQL While Preserving the Latest
In a database, it's common to encounter duplicate records, particularly in tables with unique identifiers. In MySQL, you may face a situation where emails get duplicated, and you desire to retain only the latest one with the most recent ID.
To solve this problem, we can employ the following steps:
Implementation:
Consider the following MySQL table named test with columns id and email:
| id | email | |---|---| | 1 | aaa | | 2 | bbb | | 3 | ccc | | 4 | bbb | | 5 | ddd | | 6 | eee | | 7 | aaa | | 8 | aaa | | 9 | eee |
To delete duplicate emails and keep the latest ones, we can execute the following query:
DELETE test FROM test INNER JOIN ( SELECT MAX(id) AS lastId, email FROM test GROUP BY email HAVING COUNT(*) > 1 ) duplic ON duplic.email = test.email WHERE test.idThis query retrieves the latest IDs for duplicate emails and removes all duplicates with older IDs. After executing the query, the test table will appear as follows:
| id | email | |---|---| | 3 | ccc | | 4 | bbb | | 5 | ddd | | 8 | aaa | | 9 | eee |Only the latest duplicates with the highest IDs have been preserved, satisfying the requirement to maintain the most recent email addresses in the table.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3