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

北城余情 提交于 2020-07-20 03:44:21

问题


I have these two tables:

create table pwlhseis(
ma int,
hmeromhnia date,
wra time,
hmer_diek date,
ae_po int,
amka_po int,
constraint foreign key (amka_po) references pelates(amka),
primary key (ma));

And:

create table ekdromes(
ae int,
diarkeia int,
proorismos varchar(20),
kostos float,
timh float,
afeteria varchar(20),
hm_enarkshs date,
primary key (ae));

Then:

alter table ypallhloi 
  add constraint foreign key (arithmos_up) references grafeia(arithmos_g);

alter table ekdromes 
  add constraint foreign key (ae) references pwlhseis(ae_po);

The first alter works well, when I try to run the second one i get that 1822 error. What is the problem?


回答1:


You have defined the primary key to be pwlhseis(ma). That is what you should be using for foreign key references.

Personally, I name primary keys and foreign keys to match, So, this would look like:

create table pwlhseis (
    pwlhseis_id int primary key,
    . . .
);

create table ekdromes (
    ekdromes_id int primary key,
    . . .
    pwlhseis_id int,
);

alter table ekdromes 
  add constraint fk_ekdromes_pwlhseis foreign key (pwlhseis_id) references pwlhseis(pwlhseis_id);



回答2:


If you want a foreign key against pwlhseis.ae_po this column needs to have a unique constraint.

This means:

  • It's either the primary key of the table (it is not), or
  • It has an extra unique constraint.

If you want to try the second option, you can run:

alter table pwlhseis add constraint uq1 unique (ae_po);

Then you can try adding the foreign key again.



来源:https://stackoverflow.com/questions/54154101/error-code-1822-failed-to-add-the-foreign-key-constraint-missing-index-for-co

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