6

我有桌子:

Project table

id name
-------
1  A
2  B

Assignment table

id name project_id
-------------------
1  A1   1
2  A2   1
3  A3   2

我希望编写一个查询,返回每个项目以及从中创建的分配的名称,例如:

project_id  assignments
-----------------------
1            A1,A2
2            A3

有没有办法做到这一点?

4

1 回答 1

16

您可以加入表格并使用array_agg以组合逗号分隔的值

SELECT a.id, array_agg(b.name) assignments
FROM    Project a
        INNER JOIN assignment b
          ON a.id = b.project_ID
GROUP BY a.id

SQLFiddle 演示

或通过使用STRING_AGG

SELECT a.id, STRING_AGG(b.name, ', ' ORDER BY b.name) assignments
FROM    Project a
        INNER JOIN assignment b
          ON a.id = b.project_ID
GROUP BY a.id

SQLFiddle 演示

于 2012-10-23T07:56:04.497 回答