简体   繁体   English

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

[英]SQL update and increment column using a subquery from the same table

Here's my fiddle . 这是我的小提琴 My query: 我的查询:

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; 

produces values 1, 2, 2, 2 for foo_ids (subquery only run once?) but I'd like it to give me 1, 2, 3, 4 生产值1, 2, 2, 2为foo_ids(子查询只运行一次?),但我想它给我的1, 2, 3, 4

how about this? 这个怎么样?

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

UPDATE 1 更新1

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

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