I have a couple tables that look like this:
___________ ___________ | Books | | Tags | |-----------| |-----------| | book_id | | tag_id | | book_name | | tag_name | ----------- -----------
And a join table that connects the “many-to-many relationship”:
___________ | Books/Tags| |-----------| | book_id | | tag_id | -----------
I want to do a query that’s kind of like this:
SELECT book_name, tag_name FROM books, tags WHERE tag_name = 'fiction'
Is there any way to “attach” the books table to the tags in the query since they have a join table between them? Or do I have to do three queries, one to get the tag_id, another to get the book_id matching the tag_id, and a third to get the book_name matching the tag_id?
Yes you can do; with a JOIN:
This will return a list of books which have the ‘fiction’ tag.
Alternatively you can do it with subqueries:
Or: