Update duplicate rows with duplicated found id

試著忘記壹切 提交于 2019-12-11 06:50:02

问题


i have table like :

id     name    description
1      foo      
2      bar
3      foo

i want update description with id of duplicated row . something like:

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

How can i do this in Mysql


回答1:


This query will return all duplicated ids with a comma separated list of ids that share the same name:

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

and this query will update the description:

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, ')')

please see a working fiddle here.



来源:https://stackoverflow.com/questions/38561766/update-duplicate-rows-with-duplicated-found-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!