删除mysql中值等于某个值的重复行


removing duplicate row from mysql where value equals something

我已经走到了互联网的尽头,我被卡住了。虽然我能找到部分答案,但我无法修改它使其发挥作用。

我有一个名为myfetcher的表,类似于:

+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| fid_id      | int(11)      | NO   | PRI | NULL    | auto_increment |
| linksetid   | varchar(200) | NO   |     | NULL    |                |
| url         | varchar(200) | NO   |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

url字段有时会包含重复数据,但我只需要字段linksetid等于X的地方,而不是删除表中的所有重复数据。

下面的SQL删除了表中的所有重复项(这不是我想要的)。。。但我想要的只是字段CCD_ 5中的设置范围内的重复项。我知道我做错了什么,只是不确定是什么。

DELETE FROM myfetcher USING myfetcher, myfetcher as vtable 
WHERE (myfetcher.fid>vtable.fid)
  AND (myfetcher.url=vtable.url)
  AND (myfetcher.linksetid='$linkuniq')

只删除linksetid=X的记录。第一个EXISTS检查情况,当所有记录都具有linksetid=X时,则只剩下一个具有min(fid)的记录。存在linksetid<>的记录时的第二个EXISTS检查情况X,则所有linksetid=X的记录都将被删除:

注意:此查询适用于Oracle或MSSQL。对于MYSql,使用下一个解决方法:

DELETE FROM myfetcher 
where (myfetcher.linksetid='$linkuniq')
      and 
      (
      exists
      (select t.fid from myfetcher t where 
                 t.fid<myfetcher.fid 
                 and 
                 t.url=myfetcher.url
                 and 
                 t.linksetid='$linkuniq')
      or 
      exists
      (select t.fid from myfetcher t where 
                 t.url=myfetcher.url
                 and 
                 t.linksetid<>'$linkuniq')
       ) 

在MYSql中,不能将update/delete命令与目标表的子查询一起使用。所以对于MySql,您可以使用以下脚本。SqlFiddle演示:

create table to_delete_tmp as 
select fid from myfetcher as tmain 
     where (tmain.linksetid='$linkuniq')
      and 
      (
      exists
      (select t.fid from myfetcher t where 
                 t.fid<tmain.fid
                 and 
                 t.url=tmain.url
                 and 
                 t.linksetid='$linkuniq')
      or 
      exists
      (select t.fid from myfetcher t where 
                 t.url=tmain.url
                 and 
                 t.linksetid<>'$linkuniq')
       ) ;
delete from myfetcher where myfetcher.fid in (select fid from to_delete_tmp);
drop table to_delete_tmp;