mardi 2 juin 2015

Selecting many items, which themselves have many items, in a single query?

I have an database representing a book collection. It looks like this:

books table

id    |    title            |    year    |    author_id
--------------------------------------------------------
1       How to Read              1985            7
2       A Dream of Spring        2041            14
3       Tour Guide               2010            40

tags table

id    |    tagname
-------------------
1        nonfiction
2        fiction
3        poetry
4        sci-fi
5        magical realism
6        detective

books_tags_links table

book    |    tag
------------------
8            4
10           1
10           4
10           5
8            2

There is a one-to-many relationship between books and tags: a book can have multiple tags, like 'fiction, detective, sci-fi'.

What I'd like to know is: is it possible for me to select all books, and all tags associated with each book, in a single query? I don't know what the result would look like -- a jagged array, I suppose, each book having a different number of tags?

My ultimate aim is to output a HTML table where each row is a book, with the tr element having a data-tag property for each tag that book's been given, so that I can use JavaScript to hide or show books with some combination of tags. Thus far I can only imagine how to do it by issuing a separate select tags query for every book in the list, but that could mean making thousands of database requests, and I want to know if there's a smarter way to do it.

I am using SQLite at the moment, but if there's a solution exclusive to Postgres or MySQL I'd still be interested in learning about it.

Aucun commentaire:

Enregistrer un commentaire