简体   繁体   中英

Fetching data from many-to-many relationships

I want to fetch the title from book table and the subject name from subject table for all the books of a certain author

Here is the tables relationships

在此处输入图片说明

在此处输入图片说明

I have tried to select the title and the subject from the tables but I can't get it to work with the many to many relationship

SELECT book_title,subject_name FROM book,subject WHERE $subject_ID = subject_ID INNER JOIN book_author ON author_ID = '$author_ID'

I thought about making two separate queries, if someone could help me on that I would be really glad.

Try this one:

SELECT book_title, subject_name
FROM Book
INNER JOIN Book_Author ON Book.book_ISBN = Book_Author.book_ISBN
INNER JOIN Author ON Book_Author.author_ID = Author.author_ID
INNER JOIN Subject ON Subject.subject_ID = Book.subject_ID
WHERE author_lastname = [whatever];

And nice job posting the model :)

Edit to match the exact need:

SELECT book_title, subject_name
FROM Book
INNER JOIN Book_Author ON Book.book_ISBN = Book_Author.book_ISBN
INNER JOIN Subject ON Subject.subject_ID = Book.subject_ID
WHERE author_ID = '11';

And by the way, you're having an "Column 'author_ID' in where clause is ambiguous" because this column appears both in Book_Author and Author. That's why you have to prefix it with the table name :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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