如何使用增量值更新一组记录
我有一个包含“step_ID”、“goal_ID”和“step_number”列的表。
step_ID 将是主自动递增键
goal_ID 将各个步骤分组为特定目标
目前,step_number 到处都是 0,新创建的
我想更新表,以便对于每组类似的“goal_ID”,按 step_ID 排序,step_number 设置为 0、1、2、3 等。
换句话说,我想对给定目标的步骤进行编号,从 0 到有多少个目标,按照 step_ID 的升序排列。
我尝试了显而易见的方法:
$query = " 更新步骤 SET step_num = step_num + 1 WHERE goal_ID='689' ORDER BY step_ID";
但这只是将所有行设置为 1(如预期)。
我还尝试使用各种子查询,但收到一条错误消息,指出我无法更新 FROM 子句中使用的表。
想法?
I have a table with columns "step_ID", "goal_ID" and "step_number".
step_ID would be the primary, auto-incremented key
goal_ID groups the various steps into specific goals
step_number is currently 0 everywhere, newly created
I want to UPDATE the table so that step_number is set to 0, 1, 2, 3, etc. for every group of similar "goal_ID", ordered by the step_ID.
Said a different way, I'd like to number the steps for a given goal from 0 to however many goals there are, in ascending order of step_ID.
I tried the obvious:
$query = " UPDATE steps SET step_num = step_num + 1 WHERE goal_ID='689' ORDER BY step_ID";
but that just sets all the rows to 1, (as expected.)
I tried also using various subqueries but I got an error saying I couldn't update a table used in the FROM clause.
Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将查询分成 2 个,并使用 mysql 用户定义变量
喜欢
Try break the query into 2, and make use of mysql user defined variables
like
编辑
看起来您在 MySQL 中遇到了有关包含相关子查询的更新查询的错误。以上是标准化版本。您可以像这样解决 MySQL 中的限制:
另一种解决方案:
EDIT
Looks like you are running into a bug in MySQL with respect to Update queries that contain correlated subqueries. The above would be the standardized version. You can work around the limitation in MySQL like so:
Another solution: