3

我正在尝试将 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

我该如何解决?请耐心等待,因为我确实查看了一些有关如何操作的网站,但我得到了相同的结果。

4

2 回答 2

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);

或者

ALTER TABLE ITEM
ADD CONSTRAINT FK_CATEGORY_NAME
FOREIGN KEY (SOME_OTHER_EXISTING_COLUMN)
REFERENCES CATEGORY (CATEGORY_NAME);
于 2013-07-15T17:19:20.337 回答
1

您必须首先在单独的alter 语句中添加该列:

alter table item add column category_name varchar(35);

外键约束只创建表之间的关系——它们不创建所涉及的列。

于 2013-07-15T17:17:36.490 回答