【问题标题】:Concatinating rows in postgresql在 postgresql 中连接行
【发布时间】:2016-07-16 04:55:06
【问题描述】:

我在 postgres 中有多对多的关系,即书籍和作者。作者可以有很多书,书也可以有很多作者。 我还有一个只包含 author_id 和 book_id 的连接表。 为简单起见,假设我的 authors 表有一个 id,full_name,而我的 books 表有一个 id,title。 这是一些示例数据。

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

我想要的是一个返回类似这样的查询

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

现在我正在选择标题,作者在所有三个表上都使用连接,这给了我这个:

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

我正在使用 javascript 来构建一组作者及其结果,这工作正常,但如果有人有办法在 sql 中执行此操作,我很乐意看到它。

谢谢!

【问题讨论】:

    标签: postgresql concatenation


    【解决方案1】:

    又在谷歌上搜索了一下,终于弄明白了:

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 2017-03-16
      相关资源
      最近更新 更多