Igo*_*nko 6 mysql variables insert user-defined
我需要在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");
Run Code Online (Sandbox Code Playgroud)
这个例子不起作用并插入0.我做错了什么?
Mic*_*ski 15
无需将其存储在变量中.您可以LAST_INSERT_ID()
在以下INSERT
语句中调用.
INSERT INTO `comments`(`id`, `post_id`) VALUES (NULL, LAST_INSERT_ID());
Run Code Online (Sandbox Code Playgroud)
...除非您有多个插件要使用该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);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13418 次 |
最近记录: |