简体   繁体   English

从内部联接中的联接表中获取数据

[英]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 :一个在表bookbook_to_genre之间,另一个在表book_to_genreGenre之间

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 - 加入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM