使用同一个表中的子查询进行SQL更新和增量列

时间:2013-05-02 01:12:26

标签: mysql sql

这是my fiddle。我的问题:

update foos
set foo_id = ((SELECT max_foo_id FROM (SELECT MAX(foo_id) AS max_foo_id FROM foos) AS temp_foos) + 1)
where foo_id is null; 

为foo_ids生成值1, 2, 2, 2(子查询只运行一次?)但我希望它能给我1, 2, 3, 4

1 个答案:

答案 0 :(得分:2)

怎么样?

UPDATE  foos a
        INNER JOIN
        (
            SELECT  a.bar_ID,
                    @rn := @rn + 1 row_Num
            FROM    foos a,(SELECT @rn := (SELECT MAX(foo_ID) FROM foos)) b
            WHERE   a.foo_ID IS NULL
        ) b ON a.bar_ID = b.bar_ID
SET     a.foo_id = b.row_Num

更新1