创建引用复合主键父级的外键的问题

时间:2019-10-13 15:02:02

标签: mysql

在我粘贴的mysql代码中,第二个外来actor_id_FK无法添加错误(1215无法添加外键约束)。问题出在哪里?

create table castings
(
    movieid int,
    actorid int,
    primary key (movieid, actorid)
);

create table movies
(
    id int primary key
);

create table actors
(
    id int primary key
);

alter table movies
add constraint movies_id_FK
foreign key (id) references castings(movieid);

alter table actors
add constraint actors_id_FK
foreign key (id) references castings(actorid);

1 个答案:

答案 0 :(得分:0)

您对外键的概念向后。该定义在 other 表中,而不是在定义主键的位置。所以:

alter table castings add constraint fk_castings_movie_id
    foreign key (movieid) references movies(id);