简体   繁体   English

SQL 更新列并为每一行使用列的最大值

[英]SQL update column and use max value of a column for each row

I am trying to update Program table and use max value of program.programOrder + 1 for each row.我正在尝试更新Program表并为每一行使用program.programOrder + 1的最大值。 programOrder has to be unique so I don't want to use the same value for all updates and ideally I want to recalculate max value for each row. programOrder必须是唯一的,所以我不想对所有更新使用相同的值,理想情况下我想重新计算每一行的最大值。

I get the following error:我收到以下错误:

You can't specify target table 'p' for update in FROM clause您不能在 FROM 子句中指定目标表“p”进行更新

update Program p
set p.programOrder = (select max(programOrder) + 1 from Program)
where isActive = false;

I appreciate any help or hint.我感谢任何帮助或提示。

There are different ways to do this.有不同的方法可以做到这一点。 Probably the simplest uses variables.可能最简单的使用变量。 That is something like this:那是这样的:

select @rn := max(programOrder)
from program;

update Program p
    set p.programOrder = (@rn := @rn + 1)
    where isActive = false;

Note that such use of variables is deprecated in the most recent version of MySQL, but this is still probably the most convenient method.请注意,在最新版本的 MySQL 中不推荐使用这种变量,但这可能仍然是最方便的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM