1

如果我可以从这种查询的多对多关系中产生这个结果:

SELECT x1.id AS id1, x3.id AS id3
 FROM humans x1
   LEFT JOIN memberships x2
     ON x1.id = x2.human_id
   LEFT JOIN groups x3
     ON x2.group_id = x3.id
 WHERE x1.id IN ( 1,2,3,4 )
 ORDER BY 1,2

id1 | id3 
----+----
1   | A
1   | B 
1   | C
2   | D
2   | E
3   | F
4   | (null)
5   | G
5   | Z

如何将其转换为这种表格?

id1 | id3s
----+--------
1   | A, B, C
2   | D, E
3   | F
4   | (null)
5   | G, Z
4

1 回答 1

3

使用string_agg和分组:

SELECT x1.id AS id1, string_agg(x3.id,',' order by x3.id asc) AS id3s
 FROM humans x1
   LEFT JOIN memberships x2
     ON x1.id = x2.human_id
   LEFT JOIN groups x3
     ON x2.group_id = x3.id
 WHERE x1.id IN ( 1,2,3,4 )
 GROUP BY x1.id
 ORDER BY 1
于 2013-09-18T17:37:07.083 回答