[英]How to use last_insert_id() in 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
以上不起作用,它無法識別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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.