MySQL - 关系表 - 如何创建多个关系?

时间:2014-12-14 16:00:51

标签: mysql foreign-keys relational-database

我的数据库中有两个表。

Table 1 : book
book_id (Primary & Auto Increment)
book_name
writer_id (Foreign Key from writer table, selected as index)

Table 2 : writer
writer_id (Primary & Auto Increment)
writer_name

我只能在一本书中添加一位作家,但一本书可以由两位或更多位作家撰写。我怎样才能做到这一点?

我以为我可以创建两个名为writer_2和writer_3的表(因为大多数书都是由1,2或3个作者编写的)并将它们作为外键添加到我的表中,但我对其他解决方案持开放态度。

我使用的是phpmyadmin,我的表存储引擎是InnoDB。

2 个答案:

答案 0 :(得分:1)

您需要一个将书写者分配给书籍的联结表。这将是:

create table BookWriter (
    Book_Id int not null,
    Writer_Id int not null,
    foreign key (Book_id) references book(book_id),
    foreign key (Writer_Id) references writer(writer_id)
);

请注意,您可以在此表中包含其他信息,例如别名:

create table BookWriter (
    Book_Id int not null,
    Writer_Id int not null,
    Alias varchar(255),
    foreign key (Book_id) references book(book_id),
    foreign key (Writer_Id) references writer(writer_id)
);

例如," Kilgore Trout"谁写了一本名为" Venus on the Half-Shell"真的是Kurt Vonnegut。

答案 1 :(得分:1)

您正在寻找的是多对多的关系。

Table 3 : bookwriter
writer_id
book_id

Here you can get more details,也是google。