开发者

Can I do an SQL query on a table and its join table at the same time?

开发者 https://www.devze.com 2023-02-14 14:09 出处:网络
I have a couple tables that look like this: ______________________ Books|| Tags开发者_如何学Go|

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号