Getting error 1822 in MySQL when trying to create a foreign key

流过昼夜 提交于 2021-01-29 09:55:26

问题


I am getting an error when creating a foreign key. The error is 1822 and it says the following:

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

I have read similar question and the problem seems to be, that the column that we need to create a foreign key on, does not have same datatype as the column that is referenced to.

However, I have no idea how the two columns are different to one another. Both are primary keys, with same name and type varchar(255). Below is the MySQL code.

Is there a difference between the two "version" columns? Or is the problem something else?

alter table Recipe drop column version;
alter table Changes drop column version;
alter table Recipe add column version varchar(255);
alter table Changes add column version varchar(255);
alter table Recipe drop primary key, add primary key(recipeID, version);
alter table Changes drop primary key, add primary key(newRecipeID, version);
alter table Changes add foreign key(version) references Recipe(version);

回答1:


In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html in your example you have no such key in recipe for alter table Changes add foreign key(version) references Recipe(version



来源:https://stackoverflow.com/questions/56078681/getting-error-1822-in-mysql-when-trying-to-create-a-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!