数据库
首页 > 数据库> > mysql-删除SQL数据库中的重复项

mysql-删除SQL数据库中的重复项

作者:互联网

我需要从看起来像这样的表中删除重复项:

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_title = 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

我究竟做错了什么?

解决方法:

您可以在post_title = 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

标签:sql-delete,sql,mysql
来源: https://codeday.me/bug/20191120/2043042.html