从一个表中选择单个列的一些数据并插入MySql中的另一个表

时间:2016-09-07 06:45:35

标签: mysql

我的查询:

  INSERT INTO `test` (`name`) 
    SELECT DISTINCT c4
          FROM `imp_asset` WHERE c4 !='' ORDER BY c4 ASC;

Error Code: 1062
Duplicate entry '0' for key 'PRIMARY'

我的测试表:

Field   Type
id      int(11) NOT NULL
name    varchar(200) NULL

2 个答案:

答案 0 :(得分:0)

尝试将您的表格设为:

mysql> CREATE TABLE test(
  id      int(11) NOT NULL,
  name    varchar(200) NULL,
  PRIMARY KEY (id))

或者如果已经创建了表,那么尝试使用ALTER语句对其进行更改。

alter table test modify column id INT auto_increment;

答案 1 :(得分:0)

问题是ID是INT类型并且是主键,但是在插入查询中,您没有为ID指定任何值,并且没有定义默认值。

您必须将ID列设为auto_increment:

alter table test modify column id int auto_increment;

请参阅example fiddle here

相关问题