【问题标题】:Foreign-Referencing a composite Key that has individual columns that cannot be unique外部引用具有不能唯一的单个列的复合键
【发布时间】:2021-03-25 03:25:24
【问题描述】:

我是 SQL 新手,在 MySQL 中创建表时遇到以下错误:

source path\create_bookAuthor_table.sql ERROR: 1822: Failed to add the foreign key constraint. Missing index for constraint 'book_author_ibfk_1' in the referenced table 'author'

我有一个 Author 表,它与 Book 表具有 M-N 关系,其中一位作者可以创作多本书,而一本书可以由许多作者创作。

因此,我需要创建一个名为 BookAuthor 的联结表,它实际上可以显示作者创作的书籍,或者更确切地说是每本书的作者。

我不能让名字和姓氏唯一,因为很多人可以共享一个名字。

我想知道如何在考虑到这一点的情况下强制执行外键?

我的 Book 代码如下:

create table book (
  isbn varchar(20) not null,
  '
  '
  '
  primary key(isbn),
  
); 

作者:

create table author (
  first_name varchar(20) not null, 
  last_name varchar(20) not null, 
  primary key(last_name, first_name)
); 

对于引发错误的 BookAuthor:

create table book_author (
  isbn varchar(20) not null,
  first_name varchar(20) not null, 
  last_name varchar(20) not null, 
  primary key(isbn, first_name, last_name),
  foreign key(first_name, last_name) references author(first_name, last_name),
  foreign key(isbn) references book(isbn)
); 

【问题讨论】:

  • 旁注:名字和姓氏可能不是好键。在现实世界中,同名的作者可能不止一位。
  • 我同意你的看法。汤姆在下面提到了这一点,我会考虑到这一点。

标签: mysql


【解决方案1】:

您在 author 表中的主键是 last_name, first_name,在 book_author 表中的外键是 first_name, last_name

【讨论】:

  • 它们的列出顺序真的很重要吗?我尝试交换它们并且错误仍然存​​在。另请注意,错误提到问题在于缺少索引。
  • 我在尝试你的 create 语句时遇到了一个错误,直到我交换了它们然后我没有收到错误。
  • @DavidM:更准确一点:名字和姓氏在REFERENCES 子句中交换。那是实际的问题。您可以将外键保留为(first_name, last_name),但使用REFERENCES author (last_name, first_name),它不会抛出错误,因为两列都是varchar(20)。但当然,这也会迫使您交换列的含义,然后更改它们的名称很有用,您最终会再次得到(last_name, first_name) REFERENCES author (last_name, first_name)
  • 事实上,问题在于名字和姓氏的顺序。尽管它看起来微不足道,但它确实是重要的。现在可以了!谢谢
  • 很高兴你把它整理好了,请把答案打勾,谢谢。
【解决方案2】:

恕我直言,您的主键不应该是有意义的数据(它总是会让人流泪)。

我建议使用整数链接。

【讨论】:

  • 我同意。人工 int 键可能会做得更好
猜你喜欢
  • 1970-01-01
  • 2015-02-24
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多