我有一个带有重复的products_model字段的表(产品)。
我需要将它们改为一些新的价值。
我可以选择它们:SELECT * FROM products GROUP BY products_model HAVING count(*) >=2
我需要更改products_model = products_model + RANDOM NUMBER
谢谢
答案 0 :(得分:0)
鉴于两个字段都是VARCHARS,这可以完成工作,将products_model和products_id连接到下划线
update products p1,
products p2
set
p1.products_model = concat(p1.products_model, '_', p1.products_id),
p2.products_model = concat(p2.products_model, '_', p2.products_id)
where
p1.products_model = p2.products_model
and p1.products_id > p2.products_id
在:
id products_model products_id
1 A a
2 A b
3 B a
4 C a
5 C b
后:
id products_model products_id
1 A_a a
2 A_b b
3 B a
4 C_a a
5 C_b b
答案 1 :(得分:0)
这使用变量为具有相同模型的产品分配序号。然后它会更新除第一个之外的所有内容,以便在型号名称后面显示序号:
update products p join
(select p.*,
(@rn := if(@pm = products_model, @rn + 1,
if(@pm := products_model, 1, 1)
)
) as seqnum
from products p
order by products_model
) pp
on p.id = pp.id cross join
(select @pm := '', @rn := 0) vars
set products_model = concat_ws('_', products_model, seqnum)
where seqnum > 1;