【问题标题】:MySQL, can't create foreign keyMySQL,无法创建外键
【发布时间】:2013-10-05 13:07:52
【问题描述】:
    create table movie(

    movieTitle varchar(40)
            not null

,   yearReleased year
            check (not year > year(current_date))

,   movieLength int(3)
            null

,   constraint coPKmovie
    primary key (movieTitle, yearReleased)
);

create table person(

    personName varchar(40)
            not null

,   secondName varchar(40)
            not null

,   dateOfBirth datetime
            not null

,   yearCareerStarted year
            not null
            check (not year > year(current_date))

,   bornCountry char(03)
            not null

,   constraint coPKperson
    primary key (personName, secondName)
);

create table participant(

    partPersonName varchar(40)
            not null

,   partSecondName varchar(40)
            not null

,   movieTitle varchar(40)
            not null

,   jobTitle varchar(30)
            not null

,   constraint coPKpart
    primary key (partPersonName, partSecondName, movieTitle, jobTitle)

);


alter table participant
    add constraint partFKname foreign key (partPersonName)
    references person (personName)

,   add constraint partFKSecond foreign key (partSecondName)
    references person (secondName)

,   add constraint partFKmovie foreign key (movieTitle)
    references movie (movieTitle)

    on delete cascade
    on update cascade;

谁能解释为什么我想从表参与者 partSecondName 到表 person , secondName 创建外键时总是出错。我不想听为什么我不在我的数据库中使用任何 id,我只是在没有它们的情况下练习。提前致谢! :)

【问题讨论】:

  • person 的 FK 错误,你应该同时对 name 和 second name 放置一个约束,而不是单独的。
  • 非常感谢 Matteo Tassinari,它现在可以工作了!哦,现在我知道了:)谢谢:)

标签: mysql database database-design mysql-workbench


【解决方案1】:

"8. 关系中的一个字段是组合(复合)键的一部分,并且没有它自己的单独索引。即使该字段有一个索引作为复合键的一部分,您也必须创建一个单独的仅为该关键字段建立索引,以便在约束中使用它。”

查看这篇旧帖here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 2014-02-26
    • 2020-08-14
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多