SQL删除名称相似的重复行

时间:2012-02-07 00:01:07

标签: sql

我的表包含名称如下的条目:

12345
A12345
234567
A234567
A99999

我想删除包含表中存在xxxxx的Axxxxx的行。所以在我的例子中,我想离开:

12345
234567
A99999

但删除了A12345和A234567,因为12345和234567在表格中......

5 个答案:

答案 0 :(得分:1)

delete 
  from #mytable 
 where exists ( select 'x' 
                  from #mytable b
                 where #mytable.col = 'A' + b.col );

答案 1 :(得分:0)

这将删除Axxxxx的所有行,其中有一行xxxxx:

delete from mytable
where name in (
    select CONCAT('A', name)
    from mytable
    where name not like 'A%')
)

编辑:

我在之前的版本中反转了逻辑

答案 2 :(得分:0)

delete from mytable 
where name in (select b.name
  from mytable a
  INNER JOIN mytable b
    on a.name = SubString(b.name, 1, LEN(b.name))
  WHERE Substring(a.name, 0, 1) <> 'A' AND Substring(b.name, 0, 1) = 'A'
    )

试试这个。你可能需要twig substring。但是你明白了。

答案 3 :(得分:0)

这就是我的想法:

delete from Data2 where id in (
    select d.id from Data d
    left join Data1 d1 on (d.id = CONCAT('A', d1.id))
    where d1.id is not null
)

你可以玩它here

这是一个带子字符串的查询...但我觉得效率稍差(稍后可以告诉我们):

delete from Data where id in (
    select d2.id from Data1 d1
    join Data2 d2 on (d1.id = substring(d2.id, 2))
);

注意mysql substring认为第一个字符编号为1而不是0。

你可以玩它here

答案 4 :(得分:0)

DELETE 
  FROM MyTable
 WHERE name IN (
                SELECT name
                  FROM MyTable AS T1
                INTERSECT
                SELECT 'A' + name
                  FROM MyTable AS T1
               );