Can I do an SQL query on a table and its join table at the same time?
I have a couple tables that look like this:
___________ ___________ | Books | | Tags 开发者_如何学Go| |-----------| |-----------| | 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 have the following query:
SELECT book_name, tag_name FROM books
JOIN books_tags ON books.book_id = books_tags.book_id
JOIN tags ON tags.tag_id = books_tags.tag_id
WHERE books.book_id = 283
And the following (for books that aren't tagged):
SELECT book_name FROM books WHERE books.book_id = 283
Is there a way to merge those two queries into one?
You want a LEFT join
SELECT book_name,
tag_name
FROM books
LEFT JOIN books_tags
ON books.book_id = books_tags.book_id
LEFT JOIN tags
ON tags.tag_id = books_tags.tag_id
WHERE books.book_id = 283
Do your first query but use a LEFT JOIN
for the first join clause. A left join in this case gives you all records from the books table, regardless of matches, along with matching rows that are joined.
you could (thanks for the comment!) use union . I am not sure what you mean with " merge those two queries into one "
SELECT book_name, tag_name FROM books JOIN books_tags ON books.book_id = books_tags.book_id JOIN tags ON tags.tag_id = books_tags.tag_id WHERE books.book_id = 283
UNION
SELECT book_name,'' FROM books WHERE books.book_id = 283
You can use LEFT JOIN instead of jOIN to merge both queries.
Take a look at this documentation.
精彩评论