在mysql中插入查询的问题

时间:2013-11-27 00:13:08

标签: 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错误(应该由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。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

如您所知LAST_INSERT_ID()AUTO_INCREMENT ed列插入的值。NULLAUTO_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()吗?还是只是提问?