如何在 MySQL 中使用 last_insert_id()?

diy*_*iya 1 mysql

我的 SQL 语句是这样的:

INSERT INTO foo (val1) VALUES('v1');      -- ID in first table
foo_id = SELECT last_insert_id();

INSERT INTO bar (val2) VALUES ('v2');     -- ID in second table
bar_id = SELECT last_insert_id();

INSERT INTO foobar (foo_id, bar_id, val3)
VALUES (foo_id, bar_id, 'text');          -- third table
Run Code Online (Sandbox Code Playgroud)

以上不起作用,它无法识别foo_id = statement.

scr*_*gar 5

INSERT INTO foo (val1) VALUES ('v1');     -- ID in first table
SET @foo_id = last_insert_id();

INSERT INTO bar (val2) VALUES ('v2');     -- ID in second table
SET @bar_id = last_insert_id();

INSERT INTO foobar (foo_id, bar_id, val3)
VALUES (@foo_id, @bar_id, 'text');        -- third table
Run Code Online (Sandbox Code Playgroud)