Lazarus Rising
Lazarus Rising

Reputation: 2685

Get data from a join table in inner join

I have the following four tables:

Subscription:

book_id, duration, subscriber

Book:

book_id, book_name

Genre:

genre_id, genre_name

book_to_genre:

genre_id, book_id

For a certain user (subscriber) I would like to get all rows from subscription. The book name should be fetched from table Book. I know this is done with an inner join:

SELECT Book.book_name, Subscription.duration from Subscription INNER JOIN Book on Subscription.book_id = Book.book_id where Subscription.subscriber = "somevalue";

What if I would like to fetch genre_name from table Genre, where Genre.genre_id = book_to_genre.genre_id for that book?

Upvotes: 0

Views: 65

Answers (1)

Jocelyn
Jocelyn

Reputation: 11413

Here is a modified version of your initial query that will return genre_name:
- I added the field genre_name in the SELECT part
- I added table aliases to make it easier to read
- I added 2 INNER JOIN: one between tables book and book_to_genre, the other between tables book_to_genre and Genre

SELECT b.book_name, s.duration, g.genre_name
FROM Subscription s
INNER JOIN Book b on s.book_id = b.book_id
INNER JOIN book_to_genre bg ON b.book_id = bg.book_id
INNER JOIN Genre g ON bg.genre_id = g.genre_id
where s.subscriber = "somevalue";

Documentation:
- SELECT
- JOIN

Upvotes: 1

Related Questions