Home > Database > Mysql Tutorial > How to Delete Duplicate Rows in a MySQL Table When the Target Table is in the FROM Clause?

How to Delete Duplicate Rows in a MySQL Table When the Target Table is in the FROM Clause?

DDD
Release: 2024-11-01 11:15:30
Original
379 people have browsed it

How to Delete Duplicate Rows in a MySQL Table When the Target Table is in the FROM Clause?

Deleting Duplicate Rows from a Table in MySQL

When dealing with a table containing duplicate records, it becomes necessary to remove them to maintain data integrity and efficiency. In MySQL, achieving this involves identifying and deleting duplicate rows, a process that can be accomplished through specific queries.

In your case, you've already determined duplicate records based on the field empssn using this query:

SELECT COUNT(empssn), empssn FROM employee 
GROUP BY empssn 
HAVING COUNT(empssn) > 1
Copy after login

To delete the duplicate records, you attempted the following query:

DELETE FROM employee 
WHERE (empid, empssn) NOT IN (
    SELECT MIN(empid), empssn FROM employee 
    GROUP BY empssn
);
Copy after login

However, you encountered an error because MySQL does not allow the target table to be specified in the FROM clause for an update query.

To resolve this issue, one approach is to wrap the subquery in a derived table:

DELETE FROM employee 
WHERE (empid, empssn) NOT IN (
    SELECT empid, empssn FROM (
        SELECT MIN(empid) AS empid, empssn FROM employee 
        GROUP BY empssn
    ) X
);
Copy after login

By using this modified query, you effectively create a temporary, derived table (X) containing the necessary data from the employee table. The main DELETE query can then reference this derived table to delete the duplicate rows based on the unique combination of empid and empssn. This approach should resolve the error you encountered and allow you to successfully delete the duplicate records.

The above is the detailed content of How to Delete Duplicate Rows in a MySQL Table When the Target Table is in the FROM Clause?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template