這是my fiddle。我查詢:SQL更新和增量列使用同一表中的子查詢
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
這是my fiddle。我查詢:SQL更新和增量列使用同一表中的子查詢
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
這個怎麼樣?
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
有了這種方法,如果有另一個線程更新表,我會遇到併發問題? (僅供參考,表中的'id'和'foo_id'之間沒有關係。) – David 2013-05-02 01:48:47
也許是,因爲這是會話變量。 – 2013-05-02 03:26:53
如果foo_id是鍵值,爲什麼不允許數據庫提供值。他們可以做得比我們任何人都好。哦,等一下,如果你有空值,它不會是一個關鍵值。 – 2013-05-02 01:29:10
是的,foo_id中的值與自動增量ID列沒有關係。 – David 2013-05-02 01:37:56