我正在尝试将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
我该如何解决这个问题?请耐心等待我,因为我确实看过一些有关如何做的网站,但我得到的结果相同。
答案 0 :(得分:3)
您需要在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);
OR
ALTER TABLE ITEM
ADD CONSTRAINT FK_CATEGORY_NAME
FOREIGN KEY (SOME_OTHER_EXISTING_COLUMN)
REFERENCES CATEGORY (CATEGORY_NAME);
答案 1 :(得分:1)
您必须先将该列添加到单独的alter statement:
中alter table item add column category_name varchar(35);
外键约束只在表之间创建关系 - 它们也不会创建所涉及的列。