我想编写一个查询来更新每个组的重复项:
INPUT
+-------+-------+
| group | name |
+-------+-------+
| 1 | name1 |
| 1 | name1 |
| 1 | name1 |
| 1 | name2 |
| 2 | name1 |
| 2 | name1 |
| 3 | name1 |
| 3 | name2 |
+-------+-------+
OUTPUT
+-------+----------------+
| group | name |
+-------+----------------+
| 1 | name1 |
| 1 | name1 - Copy 1 |
| 1 | name1 - Copy 2 |
| 1 | name2 |
| 2 | name1 |
| 2 | name1 - Copy 1 |
| 3 | name1 |
| 3 | name2 |
+-------+----------------+
这里有类似的东西Renaming the duplicate data in sql但我的问题是如何与团体打交道。 如何命名这个重复项并不重要,但如果我能按照我的示例中指定的那样命名,那就太棒了。
最佳答案
如果你有一个主键 id
列,那么试试这个:
update (
select `group`, name, min(id) as min_id
from test
group by `group`, name
) x
join test t using (`group`, name)
set t.name =
case when t.id <> x.min_id
then concat(t.name, ' - Copy ', t.id - x.min_id)
else t.name
end
;
演示:http://rextester.com/AWEX77086
这里有另一种方式,可能比较慢,但是可以保证连续的拷贝数。
update (
select l.id, count(*) as copy_nr
from test l
join test r
on r.group = l.group
and r.name = l.name
and r.id < l.id
group by l.id
) x
join test t using (id)
set t.name = concat(t.name, ' - Copy ', x.copy_nr);
关于mysql - 在sql中重命名每个组的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49655330/