0

I have a many to many relationship in postgres that is books and authors. Authors can have many books and books can have many authors. I also have a join table that just contains the author_id and book_id. For simplicity's sake, just assume my authors table has an id, full_name and my books table has an id, title. Here is some sample data.

authors
id|full_name
------------
 1|Ben Hernandez
 2|Another Person

books
id|title
------------
 1|How to be terrible at SQL

book_author
book_id|author_id
-----------------
      1|1
      1|2

What I would like is a query that returns something like this

title                    |authors
---------------------------------
How to be terrible at SQL|Ben Hernandez,Another Person

Right now I am selecting title,author using joins on all three tables which is giving me this:

title                    |full_name
---------------------------------
How to be terrible at SQL|Ben Hernandez
How to be terrible at SQL|Another Person

and I am using javascript to build an array of authors with the results, which is working fine but if someone has a way to do this in sql, I would love to see it.

Thank you!

1 Answer 1

3

Did some more googling and finally figured out this:

select books.title, string_agg(authors.full_name, ', ') from books
  inner join book_author on book_author.book_id = books.id
  inner join authors on book_author.author_id = authors.id
group by books.title;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.