问题
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