在条件上删除SQL数据库中的重复项

时间:2015-05-15 10:05:10

标签: mysql sql sql-delete

我需要从表格中删除重复项:

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

基本上,如果有两个条目具有相同的post_title,我需要删除post_author = 1的条目,但如果post_title是唯一的,那么该条目应保持原样。

如何使用SQL查询完成此操作?

编辑:

我尝试过Mureinik建议的查询。查询如下所示:

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)

但我收到了错误:

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

我做错了什么?

3 个答案:

答案 0 :(得分:2)

您可以使用exists运算符:

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)

答案 1 :(得分:1)

您可以在post_author = 1上设置一个条件,其中有多个post_title带有临时表:

CREATE TEMPORARY TABLE t_del AS SELECT post_title 
                     FROM t 
                     GROUP BY post_title 
                     HAVING count(post_title)>1;               

DELETE FROM t 
WHERE post_author = 1 
  AND post_title IN (select post_title FROM t_del) ;

SQL Fiddle here

答案 2 :(得分:0)

使用in运算符:

delete from TableName where post_author = 1
and post_title in(select post_title from TableName group by post_title having count(*) > 1)