[英]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: 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.
书籍名称应从表格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? 如果我想从表Genre中获取genre_name,那本书的Genre.genre_id = book_to_genre.genre_id怎么办?
Here is a modified version of your initial query that will return genre_name
: 这是初始查询的修改后的版本,它将返回
genre_name
:
- I added the field genre_name
in the SELECT
part -我在
SELECT
部分中添加了genre_name
字段
- 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
-我添加了2个
INNER JOIN
:一个在表book
和book_to_genre
之间,另一个在表book_to_genre
和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";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.