使用重复找到的ID更新重复行

时间:2016-07-25 07:18:29

标签: mysql duplicates

我的表格如下:

id     name    description
1      foo      
2      bar
3      foo

我希望更新描述的ID为重复行。类似的东西:

id     name    description
1      foo     duplicate in id (3)
2      bar     
3      foo     duplicate in id (1)  

我如何在Mysql中执行此操作

1 个答案:

答案 0 :(得分:1)

此查询将返回所有重复的ID,并使用逗号分隔的共享相同名称的ID列表:

select
  t1.id,
  group_concat(t2.id)
from
  tablename t1 inner join tablename t2
  on t1.id<>t2.id and t1.name=t2.name
group by
  t1.id

此查询将更新说明:

update tablename inner join (
  select
    t1.id,
    group_concat(t2.id) dup
  from
    tablename t1 inner join tablename t2
    on t1.id<>t2.id and t1.name=t2.name
  group by
    t1.id
  ) s on tablename.id = s.id
set
  description = concat('duplicate id in (', s.dup, ')')

请参阅working fiddle here