Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicates in an SQL database on a condition

I need to remove duplicates from a table that looks like this:

id           post_author    post_title
-----------------------------------------------------------------------------
21319        1              Youngstown State University
20535        1              Yo San University of Traditional Chinese Medicine
30268        29             Yo San University of Traditional Chinese Medicine
29747        29             Yeshiva University
21964        1              Yale University
29247        29             Yale University
29497        29             Xavier University of Louisiana
21916        1              Xavier University
29862        29             Xavier University
29860        29             Wright State University-Main Campus
20915        1              Wright State University-Lake Campus
21562        1              World Mission University
30267        29             World Mission University

Basically, if there are two entries with the same post_title, I need to remove the one with post_author = 1, but if the post_title is unique then the entry should be left as is.

How can this be done with an SQL query?

EDIT:

I've tried a query suggested by Mureinik. The query looks like this:

DELETE t FROM wp_posts AS t 
WHERE t.post_author = 1 AND
EXISTS (SELECT * FROM wp_posts s 
                WHERE t.post_title = s.post_title
                AND s.post_authot != 1)

But I got error:

[Err] 1093 - You can't specify target table 't' for update in FROM clause

What am I doing wrong?

like image 695
Victor Marchuk Avatar asked May 08 '26 08:05

Victor Marchuk


1 Answers

You could use the exists operator:

DELETE FROM my_table t
WHERE  post_author = 1 AND
       EXISTS (SELECT *
               FROM   my_table s
               WHERE  t.post_title = s.post_title AND
                      s.post_author != 1)
like image 177
Mureinik Avatar answered May 09 '26 21:05

Mureinik