Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get information from another table using intermediate table

Here I have three tables authors, books_has_authors and books.

Books_has_author is an intermediate table which contains only the primary keys form other two tables. I am trying to write an sql query which will return me all the books name written by a particular author. I am new to relational database concepts as well as writing queries for relational databases. I know some join queries but I'm really confused how to use them for fetching information through an intermediate table. Any help will be appreciated ! :)

enter image description here

like image 247
AL-zami Avatar asked Nov 26 '25 21:11

AL-zami


2 Answers

You only need to add an additional JOIN, like this:

SELECT b.book_id, b.book_name, a.author_id, a.author_name
FROM books b
JOIN books_has_author ba ON ba.books_book_id = b.book_id
JOIN author a ON ba.author_author_id = a.author_id
WHERE a.author_id = xxx
like image 131
zootropo Avatar answered Nov 29 '25 11:11

zootropo


Try this:

  SELECT b.* FROM books b 
    INNER JOIN books_has_author bha 
    ON bha.books_book_id = b.book_id
    WHERE bha.author_author_id = "$$YOUR AUTHOR ID"
like image 39
Sanjay Kumar N S Avatar answered Nov 29 '25 13:11

Sanjay Kumar N S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!