0

我有以下查询:

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 错误(应该由 last_insert_id() 生成)。这是表的结构

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

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

C
id|phoneNumber|name|address
---------------------------

有人可以帮我为什么 last_insert_id() 总是返回 1。

更多信息:表 A、B 和 C 中的 id 字段是 auto_increamented。

4

2 回答 2

1

如果您多次运行,您的意思是插入 last_insert_id() + 1 吗?

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

此外,last_insert_id() 返回最后插入的自动增量列的主键。如果 A.id 不是自动增量列,则 last_insert_id 不会将插入的值更改为 A。如果 A.id 是自动增量列,则无论如何都不需要将其包含在插入中。

编辑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;
于 2013-11-27T00:15:03.593 回答
1

正如您所知道LAST_INSERT_ID()AUTO_INCREMENTed 列的插入值和生成新值NULL的力。AUTO_INCREMENT如果你使用 NULL 而不是 last_insert_id() 会怎样:

INSERT INTO A 
SELECT NULL, B.id,C.name,C.address,
FROM sample_table C JOIN other_table B ON B.phoneNumber=C.phoneNumber;

有什么理由必须使用 last_insert_id() 吗?还是只是提问?

于 2013-11-27T00:32:34.077 回答