[英]mysql query to update field with the value of other field in the same table
[英]Update the field in the table with the sequence number of the unique value of other field
我有一个带有两个字段的表“ my_table”:“名称”和“名称_id”。 字段“ name_id”是一个数字。
name| name_id
----+---------
foo | NULL
foo | NULL
bar | NULL
bar | NULL
bar | NULL
我需要使用“名称”字段唯一值的序列号更新“名称_id”字段,因此结果表如下所示:
name| name_id
----+---------
foo | 1
foo | 1
bar | 2
bar | 2
bar | 2
我为MySQL编写了一个小程序:
SET @counter := 0;
UPDATE
(
SELECT `name`, (@counter := @counter + 1) AS `newId`
FROM
(
SELECT DISTINCT `name`
FROM `my_table`
ORDER BY `name`
) AS `temp`
) AS `src` RIGHT JOIN `my_table` AS `dest` ON `dest`.`name` = `src`.`name`
SET`dest`.`name_id` = `src`.`newId`;
这个解决方案正确吗? 在哪里有更好的解决方案来完成此任务?
在MySQL中,您可以使用变量:
set @rn := 0;
set @n := '';
update my_table
set name_id = (@rn := if(@n = name, @rn,
if(@n := name, @rn + 1, @rn + 1)
)
)
order by name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.