简体   繁体   中英

MySQL I can't add a foreign key to the table

I am trying to add a foreign key in the ItemPicture table but I receive the below error. Does anyone know what causes this and how to fix it?

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'FK_Name' in the referenced table 'item_catalogue'

create table item_catalogue(
ItemNo varchar(5),
Description varchar(300),
Name varchar (30),
Size varchar(30),
Price varchar (7),
primary key (ItemNo));

create table ItemPicture(
PictureId int auto_increment,
Name varchar (30),
Picture blob,
primary key (PictureId));

alter table ItemPicture
add constraint FK_Name
foreign key (Name) references item_catalogue(name);

For a column to be a foreign key it must link to an index of the same type as the foreign key column in another table.

As in both must be INT's and indexes for example. In your example you use a VARCHAR which could be an index, but your system would work better if you store the ItemId in ItemPicture and use that as an foreign key into item_catalogue.

Also, for the sake of your sanity, use the same casing and naming system across tables. Don't have some capitalised and some not, some with underscores and some not it will complicate matters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM