12

I need to use user-defined variable in an INSERT query for MySQL, see an example bellow:

INSERT INTO `posts`(`id`) VALUES(NULL);
SET @last_insert_id = LAST_INSERT_ID();
INSERT INTO `comments`(`id`, `post_id`) VALUES(NULL, "@last_insert_id");

This example doesn't work and inserted 0. What am I doing wrong?

Igor Timoshenko
  • 1,001
  • 3
  • 14
  • 27

1 Answers1

19

There is no need to store it in a variable. You can just call LAST_INSERT_ID() inside the following INSERT statement.

INSERT INTO `comments`(`id`, `post_id`) VALUES (NULL, LAST_INSERT_ID());

... unless you have multiple inserts to perform using that id.

In that case, the proper syntax for using the variable is to do so without quotes:

INSERT INTO `posts`(`id`) VALUES (NULL);
SET @last_insert_id = LAST_INSERT_ID();
/* Several new entries using the same @last_insert_id */
INSERT INTO `comments`(`id`, `post_id`) VALUES (NULL, @last_insert_id);
INSERT INTO `comments`(`id`, `post_id`) VALUES (NULL, @last_insert_id);
INSERT INTO `comments`(`id`, `post_id`) VALUES (NULL, @last_insert_id);
INSERT INTO `comments`(`id`, `post_id`) VALUES (NULL, @last_insert_id);
INSERT INTO `comments`(`id`, `post_id`) VALUES (NULL, @last_insert_id);
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • 1
    I need to use user-defined variable. Above was a simple example. – Igor Timoshenko May 22 '12 at 15:06
  • is it consistent enough i mean if some one else or cron is doing some inserts will the SET @last_insert_id = LAST_INSERT_ID(); takes the last id from which auto increment of which table ?! – shareef Oct 22 '17 at 10:53
  • 2
    @shareef LAST_INSERT_ID() returns a value of the last ID inserted from _the current database connection_. Another user or another cron or similar would be operating on from a different database connection with its own last_insert_id values, and so the values would be consistent. – Michael Berkowski Oct 22 '17 at 12:07