我在MYSQL中有一个包含此列和数据的表。
如何更新" name"列自动像这样?
答案 0 :(得分:0)
尝试这样的事情:
update a set a.name=a.name+cast(rownum-1 as varchar) from #original a
join
(select *, row_number() OVER (partition by name ORDER BY name, id) rownum from #original)b
on a.id=b.id
where rownum<>1
答案 1 :(得分:0)
创建子查询以根据名称获取数字序列。然后相应地更新您的表。请参阅此处的演示:http://sqlfiddle.com/#!9/439b96/2
UPDATE yourTable t1
JOIN (SELECT a.id,
case when count(*)=1
then a.name
else concat(a.name,count(*)-1)
end as new_name
FROM yourTable a
JOIN yourTable b ON a.name = b.name AND a.id >= b.id
GROUP BY a.id, a.name) t2
ON t1.id=t2.id
SET t1.name=t2.new_name;
答案 2 :(得分:0)
我会用变量来做这件事。
set @n = '';
set @rn = -1;
update t
set name = concat(name,
(case when @n = name and @rn = -1
then if(@rn := 0, '', '')
when @n = name
then @rn := @rn + 1
when @n := name
then if(@rn := 0, '', '')
end)
)
order by name, id;