Home > Database > Mysql Tutorial > Why Does \'DELETE FROM employee WHERE (empid, empssn) NOT IN (...)\' Error When Removing Duplicates in MySQL?

Why Does \'DELETE FROM employee WHERE (empid, empssn) NOT IN (...)\' Error When Removing Duplicates in MySQL?

Linda Hamilton
Release: 2024-11-01 16:24:31
Original
771 people have browsed it

Why Does

Removing Duplicate Rows in MySQL Tables: Tackling the Error

To eliminate duplicate records from a table named "employee" that contains fields 'empid', 'empname', and 'empssn', first identify them using the query:

<code class="sql">SELECT COUNT(empssn), empssn FROM employee 
GROUP BY empssn 
HAVING COUNT(empssn) > 1</code>
Copy after login

However, the subsequent deletion query:

<code class="sql">DELETE FROM employee 
WHERE (empid, empssn) NOT IN (
    SELECT MIN(empid), empssn FROM employee 
    GROUP BY empssn
);</code>
Copy after login

encounters an error about specifying the target table 'employee' in the FROM clause.

Solution:

To address this error, wrap the subquery in a derived table:

<code class="sql">DELETE FROM employee 
WHERE (empid, empssn) NOT IN (
    SELECT empid, empssn FROM (
        SELECT MIN(empid) AS empid, empssn FROM employee 
        GROUP BY empssn
    ) X
);</code>
Copy after login

This modification allows you to reference the original table within the subquery and successfully delete the duplicate rows.

The above is the detailed content of Why Does \'DELETE FROM employee WHERE (empid, empssn) NOT IN (...)\' Error When Removing Duplicates in MySQL?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template