Course Resources

Search

Search IconIcon to open search

Last updated Nov 17, 2024

# JOIN Tables with Many-to-Many Relationships

# Understanding JOINs in Many-to-Many Relationships

Given our bookstore database example from the previous lesson:

# Authors Table:

AuthorIDAuthorName
1Luna Bellatrix
2Orion Stardust
3Celeste Moon

# Books Table:

BookIDTitle
101Whispers of the Galaxy
102Secrets of the Eclipse
103Shadows in the Cosmos
104Starlight Symphony
105Moonlit Myth

# BooksAuthors Joining Table:

BookIDAuthorID
1011
1022
1032
1031
1043
1053

To retrieve data that spans across these three tables, we use the SQL JOIN operation twice. Let’s see how we can use the JOIN command to fetch the list of books along with their authors’ names now that we’re representing the data with a many-to-many relationship.

# Understanding the Many to Many Relationship

1
2
3
SELECT Books.Title, Authors.AuthorName FROM Books
JOIN BooksAuthors ON Books.BookID = BooksAuthors.BookID
JOIN Authors ON BooksAuthors.AuthorID = Authors.AuthorID;
# Expected Output:
TitleAuthorName
Whispers of the GalaxyLuna Bellatrix
Secrets of the EclipseOrion Stardust
Shadows in the CosmosOrion Stardust
Shadows in the CosmosLuna Bellatrix
Starlight SymphonyCeleste Moon
Moonlit MythCeleste Moon

# 1. SELECT Books.Title, Authors.AuthorName FROM Books

# 2. JOIN BooksAuthors ON Books.BookID = BooksAuthors.BookID

# 3. JOIN Authors ON BooksAuthors.AuthorID = Authors.AuthorID

# Practice Questions

Use the Magic Store Database (SQL - W3 Magic Store Database Overview) to complete the practice questions for week.

  1. Display Order Details with Product Names: Write a query to display details of each order, including the order ID, the date it was placed, and the names of the products in the order.

# Lessons