Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.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_Sql_Last Insert Id - Fatal编程技术网

mysql中的插入查询问题

mysql中的插入查询问题,mysql,sql,last-insert-id,Mysql,Sql,Last Insert Id,我有以下疑问: insert into A select last_insert_id(),B.id,C.name,C.address, from sample_table C join other_table B on B.phoneNumber=C.phoneNumber; 我得到了重复的主键值=1错误(应该由最后一个\u insert\u id()生成)。 下面是表的结构 A id|phoneNumber|name|address ---------------------------

我有以下疑问:

insert into A select last_insert_id(),B.id,C.name,C.address,
from sample_table C join other_table B on B.phoneNumber=C.phoneNumber;
我得到了重复的主键值=1错误(应该由最后一个\u insert\u id()生成)。 下面是表的结构

A
id|phoneNumber|name|address
---------------------------

B
id|phoneNumber|email
--------------------

C
id|phoneNumber|name|address
---------------------------
有人能帮我解释一下为什么last_insert_id()总是返回1


更多信息:表A、B和C中的id字段是自动递增的。

如果要多次运行此操作,是否要插入最后一个id()+1

如果您没有多次运行该命令,那么听起来表A的PK已经为1,您需要为A.id选择一个不同的值或更新现有行

另外,last_insert_id()为自动递增列返回上次插入的主键。如果A.id不是自动递增列,则last_insert_id不会将inserts上的值更改为A。如果A.id是自动递增列,则不需要将其包含在insert中

编辑2:见下文

insert into A 
select null, B.phonenumber,C.name,C.address,
from sample_table C 
join other_table B 
  on B.phoneNumber=C.phoneNumber;

正如您所知,
LAST\u INSERT\u ID()
用于
AUTO\u INCREMENT
ed列的插入值。而
AUTO\u INCREMENT
NULL
强制生成新值。如果使用NULL而不是最后一个插入id(),该怎么办


是否有任何理由必须使用last_insert_id()?或者只是问一个问题?

没关系,因为那样它会不断返回2我不同意。脚本第一次运行时,last_insert_id()将返回1。下一次,它将返回2,因为这将是最后一次插入的PK值。这就是我想说的,先生,无论它运行多少次,它总是返回1。@Ashish With
last\u insert\u id()
(不是
+1
),那么它总是返回1,是的。还有,last\u insert\u id()的值在具有多个插入的单个语句中始终为常量。换句话说,如果复制并粘贴同一个insert 5次,并在一条语句中执行所有5次insert,则语句中该insert的所有实例的last_insert_id()值都将相同,这将引发错误。在存储过程中,行为是不同的,last_insert_id()将始终是最后一个插入的自动增量id。刚刚使用了NULL,它似乎正在工作。让查询完成。老实说,我不知道使用NULL,也不知道这种差异。
INSERT INTO A 
SELECT NULL, B.id,C.name,C.address,
FROM sample_table C JOIN other_table B ON B.phoneNumber=C.phoneNumber;