简体   繁体   中英

Is it possible to do an SQL query across two tables?

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:

SELECT b.book_name, t.tag_name FROM books b
JOIN books_tags bt ON bt.book_id=b.book_id
JOIN tags t ON t.tag_id=bt.tag_id
WHERE t.tag_name = 'fiction';

This will return a list of books which have the 'fiction' tag.

Alternatively you can do it with subqueries:

SELECT b.book_name FROM books b WHERE id IN (
    SELECT bt.book_id FROM books_tags bt
    WHERE bt.tag_id IN (
        SELECT t.tag_id FROM tags t WHERE t.tag_name='fiction'
    )
)

Or:

SELECT b.book_name FROM books b WHERE EXISTS (
    SELECT 1 FROM books_tags bt
    JOIN tags t ON t.tag_id=bt.tag_id
    WHERE t.tag_name='fiction'
)

Yes you can do this in one query, this is called a JOIN :

SELECT book_name, tag_name FROM books
    JOIN bookTags ON books.book_id = bookTags.book_id
    JOIN tags ON booksTags.tag_id = tags.tag_id
    WHERE tag_name = 'fiction';

you will need to join all three tables

SELECT books.book_name, books.tag_name FROM books, bookTags, Tags
WHERE books.book_id = bookTags.book_id
AND booksTags.tag_id = Tags.tag_id
and Tag.tag_name = 'fiction';

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