[英]How to add a primary key to a mysql table without a primary key
我需要使用現有數據向 Mysql 中的表添加主鍵。
狀態:
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| country_code | varchar(2) | YES | | NULL | |
| state_code | varchar(20) | YES | | NULL | |
| state_name | varchar(255) | YES | | NULL | |
+--------------+--------------+------+-----+---------+-------+
我創建了一個 States2 表,它是空的,其中包含一個主鍵。
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| country_code | varchar(2) | YES | | NULL | |
| state_code | varchar(20) | YES | | NULL | |
| state_name | varchar(255) | YES | | NULL | |
+--------------+--------------+------+-----+---------+-------+
我現在要做的是從 States 中獲取數據並將其復制到 States2,同時添加 Autoincrement 主鍵。
這是我嘗試過的:
mysql> insert into states2 select NULL,states.* FROM states;
ERROR 1048 (23000): Column 'id' cannot be null
復制這個並同時插入密鑰的正確方法是什么?
您明確地將null
值分配給主鍵列,這是 MySQL 不允許的(主鍵不能是null
)。
只需將主鍵列從insert
語句中分離出來,這樣就可以發生自動增量:
insert into states2 (country_code, state_code, state_name)
select country_code, state_code, state_name FROM states;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.