如何使用增量值更新一组记录

时间:2010-11-21 20:24:03

标签: php mysql increment

我有一个包含“step_ID”,“goal_ID”和“step_number”列的表格。

step_ID将是主要的,自动递增的密钥
goal_ID将各个步骤分组为特定目标 step_number当前为0,新创建

我想更新表格,以便stepNumber被设置为0,1,2,3等,用于每个类似“goal_ID”的组,由step_ID排序。

以不同的方式说,我想按照步骤ID的升序,将给定目标的步数从0编号到有多少目标。

我尝试了显而易见的事情:

  

$ query =“UPDATE步骤SET step_num = step_num + 1 WHERE goal_ID ='689'ORDER BY step_ID”;

但只是将所有行设置为1,(如预期的那样。)

我也试过使用各种子查询,但是我收到一条错误,说我无法更新FROM子句中使用的表。

思想?

2 个答案:

答案 0 :(得分:2)

尝试将查询分解为2,并使用mysql user defined variables

$db->query("SET @counter:=-1");
$db->query(UPDATE steps SET step_num = @counter:=@counter+1 WHERE goal_ID='689' ORDER BY step_ID");

答案 1 :(得分:1)

Update steps
Set step_num =  (
                    Select Count(*)
                    From steps As T1
                    Where T1.goal_ID = steps.goal_ID
                        And T1.step_ID < steps.step_ID
                    )

修改

对于包含相关子查询的Update查询,您似乎遇到了MySQL中的错误。以上是标准化版本。您可以像以下一样解决MySQL中的限制:

Update steps
Set step_num =  (
                    Select Count(*)
                    From    (
                            Select T1.step_Id, T1.goal_Id
                            From steps As T1
                            ) As Z
                    Where Z.goal_Id = steps.goal_ID
                        And Z.step_ID < steps.step_ID
                    )

另一种解决方案:

Update steps As T1
    Join    (
            Select T1.step_ID, Count(T2.step_ID) As step_num
            From steps As T1
                Left Join steps As T2
                    On T2.goal_ID = T1.goal_ID
                        And T2.step_ID < T1.step_ID
            Group By T1.step_ID
            ) As T3
        On T3.step_ID = T1.step_ID
Set step_num = T2.step_num