简体   繁体   English

MySQL矛盾插入

[英]MySQL contradiction insert

I am trying to insert into one of my tables (from the same table). 我试图插入到我的一张桌子(从同一张桌子)。 I need to change 1 of the values, so I tried to insert with select as answered here . 我需要更改其中的1个值,因此我尝试插入select作为此处的答案。 I have an auto increment pk, and would want the newly inserted pk to continue the count. 我有一个自动增量pk,并且希望新插入的pk继续计数。 so inserting would result into adding 1 to the pk. 因此插入将导致对pk加1。

INSERT INTO test.pp_publication_info
(id,
publication_fk,
template_fk,
allow_excel_upload)
SELECT 
id, 55, template_fk, allow_excel_upload
FROM pp_publication_info where id = "1";

I get a 1062 error, which is a duplicate entry for 1 for KEY PRIMARY. 我收到1062错误,这是KEY PRIMARY的1的重复条目。 I would have though that because of the AI it would +1 the ID column. 但是由于AI,我将拥有+1 ID列的信息。 SO I checked to see if I could add a ON DUPLICATE KEY UPDATE id . 因此,我检查了是否可以添加ON DUPLICATE KEY UPDATE id Unfortunately it didn't matter where I put that in the query. 不幸的是,我在查询中的位置并不重要。

So in short: can I INSERT this way, with select whilst holding the AI function? 简而言之:我可以在保持AI功能的同时通过select INSERT吗? If so, where am I going wrong and if not, are there any any alternatives? 如果是这样,我在哪里出错?如果没有,是否有其他选择?

Addition: create statement of my table: 另外:我表的创建语句:

CREATE TABLE `pp_publication_info` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`publication_fk` int(10) unsigned NOT NULL,
`template_fk` int(10) unsigned DEFAULT NULL,
`allow_excel_upload` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;

Your id column is AUTO_INCREMENT : 您的id AUTO_INCREMENT

`id` int(10) unsigned NOT NULL AUTO_INCREMENT,

This means the database will generate an identifier for you when the record is inserted. 这意味着插入记录时数据库将生成一个标识为您服务 So simply don't insert a value into that field. 因此,只需不要在该字段中插入值。 It will be populated automatically. 它将自动填充。

So something like this: 所以像这样:

INSERT INTO test.pp_publication_info
  (publication_fk,
   template_fk,
   allow_excel_upload)
SELECT 
  55, template_fk, allow_excel_upload
FROM pp_publication_info where id = 1;

After the INSERT is executed, you'll find that the id column of any new record(s) has been populated with the next value(s) in the sequence. 执行INSERT后,您会发现所有新记录的id列已填充有序列中的下一个值。 (Barring any gaps in the sequence, which could happen for any number of reasons.) (除非有任何原因,否则序列中可能没有任何缺口。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM