Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

phpmyadmin - how to delete duplicate rows from a table in mysql

I need to delete duplicate record from table in mysql. So i have a table name "employee" fields are empid, empname, empssn

for getting duplicate record i have written a query

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

Now i want to delete duplicate records. for that i have written query is.

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

you can assume records in table are

EmpId  EmpName  EmpSSN
 -------------------------------
 1  Jack      555-55-5555
 2  Joe      555-56-5555
 3  Fred      555-57-5555
 4  Mike      555-58-5555
 5  Cathy      555-59-5555
 6  Lisa      555-70-5555
 7  Jack      555-55-5555
 8  Mike      555-58-5555
 9  Cathy      555-59-5555
10  Lisa      555-70-5555
11  Lisa      555-70-5555

but i have a mysql error is

You can't specify target table 'employee' for update in FROM clause

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Does the trick of wrapping it into a derived table work for this case? (Based on http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/)

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

Edit Yep it seems to work this end.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...