Course Resources

Search

Search IconIcon to open search

Last updated Nov 17, 2024

# JOIN Tables with One-to-Many Relationships

# Understanding JOINs in One-to-Many Relationships

Given our bookstore database example from the previous lesson:

# Authors Table:

AuthorIDAuthorName
1J.K. Rowling
2George Orwell
3Leo Tolstoy

# Books Table:

BookIDTitleAuthorID
101Harry Potter1
10219842
103Animal Farm2
104War and Peace3
105Anna Karenina3

In order to retrieve data that spans across these two tables, we use the SQL JOIN operation. Let’s see how we can use the JOIN command to fetch the list of books along with their authors’ names.

1
2
SELECT Books.Title, Authors.AuthorName FROM Books
JOIN Authors ON Books.AuthorID = Authors.AuthorID; 
# Expected Output:
TitleAuthorName
Harry PotterJ.K. Rowling
1984George Orwell
Animal FarmGeorge Orwell
War and PeaceLeo Tolstoy
Anna KareninaLeo Tolstoy

This query effectively combines data from the Books and Authors tables by linking books to their respective authors by the AuthorID. The JOIN operation, facilitated by the ON clause, ensures that each book is matched with its author. The selected columns Books.Title and Authors.AuthorName are displayed in the resulting output.

To understand exactly how the SQL JOIN command works in our Authors and Books example, let’s break down the query piece by piece.

# 1. SELECT Books.Title, Authors.AuthorName

# 2. FROM Books

# 3. JOIN Authors

# 4. ON Books.AuthorID = Authors.AuthorID

# Practice Questions

  1. Write a query to list all orders, including the order ID, the date the order was placed, and the first and last name of the client who placed the order./

  2. Write a query to display a list of all products, including their name, price, and the name and address of their supplier.

# Lessons