mysql-如何向现有表添加外键?
作者:互联网
我正在尝试将Category_Name作为外键添加到ITEM表中. Category_Name存在于CATEGORY表中,这是我得到的:
mysql> use acmeonline;
Database changed
mysql> show tables;
+----------------------+
| Tables_in_acmeonline |
+----------------------+
| category |
| item |
+----------------------+
2 rows in set (0.00 sec)
mysql> describe item;
+-------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| Item_Number | int(11) | NO | PRI | 0 | |
| Item_Name | varchar(35) | YES | | NULL | |
| Model_Num | varchar(15) | YES | | NULL | |
| Description | varchar(255) | YES | | NULL | |
| Price | double(8,2) | YES | | NULL | |
+-------------+--------------+------+-----+---------+-------+
5 rows in set (0.07 sec)
mysql> describe category;
+------------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------+-------------+------+-----+---------+-------+
| Category_Name | varchar(35) | NO | PRI | | |
| ShippingPerPound | double(4,2) | YES | | NULL | |
| DiscountAllowed | char(1) | YES | | NULL | |
+------------------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)
mysql> ALTER TABLE item
-> ADD CONSTRAINT fk_category_name
-> FOREIGN KEY(Category_Name)
-> REFERENCES Category(Category_Name);
ERROR 1072 (42000): Key column 'Category_Name' doesn't exist in table
我该如何解决?请耐心等待,因为我确实查看了一些网站上的操作方法,但结果却相同.
解决方法:
您需要在ITEM TABLE上添加CATEGORY_NAME列,或将外键映射到ITEM中的另一个现有列.
要么:
ALTER TABLE ITEM
ADD CATEGORY_NAME VARCHAR(35) NOT NULL;
ALTER TABLE ITEM
ADD CONSTRAINT FK_CATEGORY_NAME
FOREIGN KEY (CATEGORY_NAME)
REFERENCES CATEGORY (CATEGORY_NAME);
要么
ALTER TABLE ITEM
ADD CONSTRAINT FK_CATEGORY_NAME
FOREIGN KEY (SOME_OTHER_EXISTING_COLUMN)
REFERENCES CATEGORY (CATEGORY_NAME);
标签:foreign-keys,sql,mysql,database 来源: https://codeday.me/bug/20191030/1969558.html