Get all insert ids in a transaction

ぐ巨炮叔叔 提交于 2019-12-12 05:39:26

问题


I have two tables in a MySQL database: "messages" and "message_tags". The "messages" table has an auto increment column "message_id". In Java I want to add a batch of messages to the database using the java.sql package. I want to do this in one transaction to save queries.

My SQL code should look something like this:

START TRANSACTION
INSERT INTO messages(`message`) VALUES ('message1');
INSERT INTO messages_tags(`message_id`, `tags`) VALUES (LAST_INSERT_ID(), 'tagfoo1');
INSERT INTO messages_tags(`message_id`, `tags`) VALUES (LAST_INSERT_ID(), 'tagbar1');
INSERT INTO messages(`message`) VALUES ('message2');
INSERT INTO messages_tags(`message_id`, `tags`) VALUES (LAST_INSERT_ID(), 'tagfoo1');
INSERT INTO messages(`message`) VALUES ('message3');
INSERT INTO messages_tags(`message_id`, `tags`) VALUES (LAST_INSERT_ID(), 'tagfoo2');
...
COMMIT

Is it possible to get all newly generated ids from the messages table back to java in a way, that they can be matched to the original messages? Something like this:

message1 => 1234
message2 => 1235
message3 => 1236
...

回答1:


you didn't specify if it's static or dynamic, but I guess you can use something like this:

START TRANSACTION
INSERT INTO messages(`message`) VALUES ('message1');
@message1:=last_insert_id();
INSERT INTO messages_tags(`message_id`, `tags`) VALUES (LAST_INSERT_ID(), 'tagfoo1');
@message2:=last_insert_id();
INSERT INTO messages_tags(`message_id`, `tags`) VALUES (LAST_INSERT_ID(), 'tagbar1');
@message3:=last_insert_id();
INSERT INTO messages(`message`) VALUES ('message2');
INSERT INTO messages_tags(`message_id`, `tags`) VALUES (LAST_INSERT_ID(), 'tagfoo1');
@message4:=last_insert_id();
INSERT INTO messages(`message`) VALUES ('message3');
INSERT INTO messages_tags(`message_id`, `tags`) VALUES (LAST_INSERT_ID(), 'tagfoo2');
@message5:=last_insert_id();
...
COMMIT

if you make

select @message1;

the result would be 1234, so you have

@message1 => 1234
@message2 => 1235
@message3 => 1236
...

but you have to specify the SQL variable manually at least you create a procedure, or a function.



来源:https://stackoverflow.com/questions/10755334/get-all-insert-ids-in-a-transaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!