我有一个父表Customers和一个子表地址。当我创建客户时,我将ADDRESS参考ID保留为0,以便稍后填写。那么现在是时候将ADDRESSES id插入Customers,但是当我运行命令时,我得到一个重复的错误,即使没有。
insert into Customers (ADDRESS) select ID from Addresses ;
ERROR 1062 (23000): Duplicate entry '0' for key 'PRIMARY'
客户
+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | NULL | |
| NAME | varchar(20) | NO | | NULL | |
| AGE | int(11) | NO | | NULL | |
| ADDRESS | int(11) | NO | | NULL | |
| SALARY | decimal(18,2) | YES | | NULL | |
+---------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
地址
+------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+----------------+
| ID | int(11) | NO | PRI | NULL | auto_increment |
| CUSTOMERID | int(11) | NO | | NULL | |
| CITY | varchar(35) | YES | | NULL | |
| COUNTRY | varchar(45) | YES | | NULL | |
+------------+-------------+------+-----+---------+----------------+
4 rows in set (0.02 sec)
客户
+----+--------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+---------+---------+
| 0 | Matt | 24 | 0 | 2200.00 |
| 1 | Andrew | 23 | 0 | 4400.00 |
| 2 | John | 30 | 0 | 1200.00 |
| 3 | Mike | 55 | 0 | 5500.00 |
| 5 | George | 45 | 0 | 2300.00 |
| 6 | Frank | 32 | 0 | 2300.00 |
| 7 | George | 45 | 0 | 2700.00 |
| 8 | Joe | 38 | 0 | 4350.00 |
| 9 | Josh | 35 | 0 | 5050.00 |
+----+--------+-----+---------+---------+
地址
+----+------------+----------+---------+
| ID | CUSTOMERID | CITY | COUNTRY |
+----+------------+----------+---------+
| 15 | 0 | Chicago | USA |
| 16 | 1 | Chicago | USA |
| 17 | 2 | London | ENG |
| 18 | 3 | New York | USA |
| 19 | 5 | New York | USA |
| 20 | 6 | New York | USA |
| 21 | 7 | Chicago | USA |
| 23 | 8 | Miami | NULL |
| 25 | 9 | Miami | NULL |
答案 0 :(得分:1)
您应该在CustomerId
中将Customers
设为自动增量键。
这是你面临的问题。因为您没有在Customer.Id
中给insert
一个值,所以MySQL倾向于分配NULL
。但是主键不能是NULL
,所以MySQL帮你将值转换为0.然后你就会在第二个插页上产生冲突(如果已经有一行0
)。
答案 1 :(得分:1)
您应该为客户表使用自动增量
`ID` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
否则使用
插入客户(ADDRESS)从地址中选择ID;
您正在尝试插入新行(但没有正确的ID ..再次为0)