mysql - Selecting many items, which themselves have many items, in a single query? -
i have database representing book collection. looks this:
books table
id | title | year | author_id -------------------------------------------------------- 1 how read 1985 7 2 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 one-to-many relationship between books , tags: book can have multiple tags, 'fiction, detective, sci-fi'.
what i'd know is: possible me select books, and tags associated each book, in single query? don't know result -- jagged array, suppose, each book having different number of tags?
my ultimate aim output html table each row book, tr
element having data-tag
property each tag book's been given, can use javascript hide or show books combination of tags. far can imagine how issuing separate select tags
query every book in list, mean making thousands of database requests, , want know if there's smarter way it.
i using sqlite @ moment, if there's solution exclusive postgres or mysql i'd still interested in learning it.
in postgres should use array_agg()
function aggregate tags linked book.
select title, array_agg(tagname) books b join books_tags_links l on l.book = b.id join tags t on l.tag = t.id group 1
in sqlite3 have similar function group_concat()
(array_agg()
returns array, group_concat()
- string).
Comments
Post a Comment