Home >Database >Mysql Tutorial >How to Delete Duplicate Rows from a MySQL Table (Versions 5.0 and Above)?

How to Delete Duplicate Rows from a MySQL Table (Versions 5.0 and Above)?

Barbara Streisand
Barbara StreisandOriginal
2024-12-25 20:20:14651browse

How to Delete Duplicate Rows from a MySQL Table (Versions 5.0 and Above)?

Deleting Duplicates from a MySQL Table

In MySQL, you may encounter a scenario where you need to remove duplicate rows from a table while ensuring unique identification through an ID column. While the provided query is valid for MySQL 5.7 and above, it doesn't work in earlier versions like 5.0.

To achieve the desired behavior in MySQL 5.0, you can rewrite the query using the IN operator rather than = for comparing IDs with the subquery result set. Additionally, you cannot directly modify a table from a subquery within the same query.

To resolve this limitation, you can either execute separate SELECT and DELETE queries or use nested subqueries to alias the result of the inner subquery. Here's an example of a nested subquery approach:

DELETE FROM posts
WHERE id IN (
    SELECT * FROM (
        SELECT id FROM posts GROUP BY id HAVING ( COUNT(id) > 1 )
    ) AS p
)

Alternatively, as suggested by Mchl, you can employ joins to delete duplicate rows by joining the table with itself based on the ID column and using the HAVING clause to filter for duplicate IDs.

The above is the detailed content of How to Delete Duplicate Rows from a MySQL Table (Versions 5.0 and Above)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn