Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL插入查询中的用户定义变量_Mysql_Variables_Insert_User Defined - Fatal编程技术网

MySQL插入查询中的用户定义变量

MySQL插入查询中的用户定义变量,mysql,variables,insert,user-defined,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"); 此示例不起作用,插入了0。我做错了什么?不需要将其存储在变量中。您只需在下面的INSERT语句中调用LAST\u

我需要在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。我做错了什么?

不需要将其存储在变量中。您只需在下面的
INSERT
语句中调用
LAST\u INSERT\u ID()

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);

我需要使用用户定义的变量。上面是一个简单的例子。它是否足够一致?我的意思是,如果其他人或cron正在执行一些插入,那么将设置@last_insert_id=last_insert_id();从哪个表的哪个自动增量中获取最后一个id@shareef LAST_INSERT_ID()返回从当前数据库连接插入的最后一个ID的值。另一个用户或另一个cron或类似用户将使用其自己的last_insert_id值从不同的数据库连接对其进行操作,因此这些值将是一致的。