In this lab you get experience using SQL junction tables.
Start with this SQL interpreter (clear out the default SQL supplied). Throughout this exercise, test your SQL commands in the interpreter, but keep a copy of all of your working commands in your text document. You can also work with a local copy of SQLite if you prefer.
We want a database that implements the following entity-relationship-diagram, where each author has written one or more books, and each book is written by one or more authors:
The trouble is there isn't any clean way to implement this with just two database tables. If each book only had one author, then the Books
table could just have AuthorID
as a foreign key. But then how would you indicate multiple authors? Instead, we will use a junction table to resolve this difficulty:
Every element of the Authors_Books
junction table represents a single author being on a single book. We would represent 4 authors on a single book by having 4 entries in the junction table: each with a different AuthorID but the same BookID. We could determine which books someone has authored by looking at all the BookIDs for that given AuthorID.
Create tables for Authors and Books, being sure to declare the primary key of each. Then create the junction table as follows. (By the way, "junction table" is only one of many different terms people use for this pattern.)
CREATE TABLE Authors_Books(
AuthorID INTEGER NOT NULL,
BookID INTEGER NOT NULL,
PRIMARY KEY (AuthorID, BookID),
FOREIGN KEY(AuthorID) REFERENCES Authors(AuthorID),
FOREIGN KEY(BookID) REFERENCES Books(BookID)
);
We say NOT NULL
because it only makes sense to have an entry in our junction table with both an author and a book; the pair of IDs together is the unique association we care about between authors and books, so we defined the primary key where each pair of IDs is unique. We are still free to have authors and books appear multiple times, as long as a given (AuthorID,BookID)
pair only appears once. The FOREIGN KEY
constraints ensure that we don't end up in a situation where a book or author gets deleted but there is still a reference to it in the Authors_Books
table.
Use insert commands to put in the following data.
Name | |
---|---|
Tolkien | |
Gamma | |
Helm | |
Johnson | |
Vlissides |
Title | Authors |
---|---|
The Lord of the Rings | Tolkien |
The Hobbit | Tolkien |
Design Patterns | Gamma, Helm, Johnson, Vlissides |
Refactoring | Gamma |
Fundamentals of Argumentation Theory | Johnson |
Pattern Hatching | Vlissides |