简体   繁体   中英

How to use last_insert_id() in MySQL?

My SQL statements like this:

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

The above is not working, it doesn't recognize the foo_id = statement .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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