我需要在 MySQL 的 INSERT 查询中使用用户定义的变量,请参阅下面的示例:

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

这个例子不起作用并插入了 0。我究竟做错了什么?

有帮助吗?

解决方案

无需将其存储在变量中。你可以打电话 LAST_INSERT_ID() 在下面的里面 INSERT 陈述。

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

...除非您要使用该 id 执行多次插入。

在这种情况下,使用变量的正确语法是不带引号:

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top