13

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?

0

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I need to use user-defined variable. Above was a simple example.
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 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.