I have two tables in my 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
I can add only one writer to a book, but a book can be written by two or more writers. How can I achieve that?
I thought I could create two tables called writer_2 and writer_3 (since most books are written by 1, 2 or 3 writers) and add them as a foreign key to my table, but I am open to alternative solutions.
I am using phpmyadmin and my table storage engine is InnoDB.
You need a junction table that assigns writers to books. This would be something like:
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)
);
Note that you could have additional information in this table, such as an alias:
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)
);
For instance, "Kilgore Trout" who wrote a book called "Venus on the Half-Shell" was really Kurt Vonnegut.
What you are looking for is a many-to-many relationship.
Table 3 : bookwriter
writer_id
book_id
Here you can get more details , also google.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.