简体   繁体   中英

Combining the many side of a many-to-one relationship into one field?

Two tables: books and authors . A book can have many authors, as in the case of a short story anthology.

books

id    |    title
--------------------
1        The Time Machine Did It
2        Snakes in Suits
3        Ghost in the Wires

authors

id    |    name
------------------------
1        Stephen King
2        John Swartzwelder
3        Robert D. Hare
4        Kevin Mitnick
5        William L. Simon
6        Steve Wozniak
7        Paul Babiak

books_authors_link

book_id    |    authors_id
---------------------------
1                2
2                3
2                7
3                4
3                5
3                6

What I'd like to do is return a table where each row is a book, and the 'authors' field is a comma-separated list of all authors, eg

query results

title                    |    authors
---------------------------------
The Time Machine Did It    John Swartzwelder
Snakes in Suits            Robert D. Hare, Paul Babiak
Ghost in the Wires         Kevin Mitnick, William L. Simon, Steve Wozniak

I've been playing around with GROUP BY and concatenation functions, and I know the answer is there somewhere, but I just can't quite figure it out. I can do it by juggling arrays and string joins around in my program itself but that's not the elegant solution I'm looking for. A tip here would be appreciated.

I'm using SQLite 3 if it's system-dependent.

You have to join both tables, group by book and apply a group_concat on the author namecolumn.

The official documentation of the function is here

And here´s another example I´ve found in stackoverflow

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