I have a relational database which schema is:
Book (ID INTEGER PRIMARY KEY, title TEXT)
Author (ID INTEGER PRIMARY KEY, name TEXT)
BookAuthor (book_id INTEGER, author_id INTEGER)
Note: obvious FOREIGN KEY constraints exist in the BookAuthor
table, but I omitted them above just to save some space
BookAuthor is a table that associates a book with one author.
Now, if I want to print out a book and its authors I can use:
SELECT book.title, author.name
FROM book
LEFT JOIN BookAuthor ON Book.id = BookAuthor.book_id
LEFT JOIN author ON author.id = BookAuthor.id
(The LEFT JOIN
is necessary if I want to list also the books that have no authors available in the database).
The output is
Book1|Author1
Book1|Author2
Book1|Author3
Book2|Author4
Book2|Author2
Book3|Author5
...
I was wondering if there is a way to join all titles in a single row, printing something like
Book1|Author1, Author2, Author3
Book2|Author4, Author2
Book3|Author5
using only SQL (of course I can postprocess the data, I was just curious if it was possible)?