3

I am trying to add Category_Name as a foreign key to the ITEM table. Category_Name exists in CATEGORY table and this is what i get:

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

How do I fix this? Please bear with me because I did look at some sites on how to do it, but I get the same results.

Mark J. Bobak
  • 13,720
  • 6
  • 39
  • 67
TheAmazingKnight
  • 2,442
  • 9
  • 49
  • 77
  • you will find your answer here http://stackoverflow.com/questions/10028214/add-foreign-key-to-existing-table – Marek Jul 15 '13 at 17:19

2 Answers2

4

You need to add the CATEGORY_NAME column on ITEM TABLE, or map the foreign key to another existing column in ITEM.

Either:

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);
Sathish
  • 368
  • 1
  • 3
  • 16
tilley31
  • 668
  • 13
  • 19
1

You must first add the column in a separate alter statement:

alter table item add column category_name varchar(35);

Foreign key constraints only create a relationship between tables - they don't also create the column(s) involved.

Bohemian
  • 412,405
  • 93
  • 575
  • 722