postgresql如何连接多个表来获取逗号分隔输出

时间:2015-12-28 20:35:09

标签: sql postgresql select join

我有以下表格:

  • table1 id,user_id,first_name,last_name
  • table2 id,user_id,company_name,first_name,last_name,partner_id
  • table3企业ID,business_name

我想创建将返回数据行的查询: user_id,(first_name last_name),(business_name,business_name ...) 当用户与多个企业关联时,如下所示: 123,John Doe,Business1,Business2

当我使用以下查询时,我可以获得一些重复的行:

SELECT table1.first_name, table1.last_name, table2.copmany_name,
       (case when concat(table1.first_name, table1.last_name) = '' then table2.company_name else concat_ws(' ', table1.first_name,table1.last_name) end) as name,
       table3.name as business_name
FROM table1
JOIN table2 ON table1.user_id = table2.user_id
JOIN table3 ON table2.partner_id = table3.id

以下是该查询的示例:

123, John Doe, Business1
123, John Doe, Business2
125, Marie Bird, Business3

我想得到:

123, John Doe, Business1, Business2
125, Marie Bird, Business3

这可能吗?

谢谢

2 个答案:

答案 0 :(得分:0)

您可以在postgresql中使用array_agg .Aggregate函数从一组输入值计算单个结果。:

SELECT table1.first_name, table1.last_name, table2.copmany_name,
       (case when concat(table1.first_name, table1.last_name) = '' then table2.company_name else concat_ws(' ', table1.first_name,table1.last_name) end) as name,
       array_agg(table3.name) as business_name
FROM table1
JOIN table2 ON table1.user_id = table2.user_id
JOIN table3 ON table2.partner_id = table3.id

答案 1 :(得分:0)

string_agg聚合函数允许您将表达式连接在一起:

SELECT   table1.first_name,
         table1.last_name,
         table2.copmany_name,
         (CASE WHEN CONCAT(table1.first_name, table1.last_name) = '' 
               THEN table2.company_name 
               ELSE CONCAT_WS(' ', table1.first_name, table1.last_name) 
          END) AS name,
         STRING_AGG(table3.name, ', ') AS business_name
FROM     table1
JOIN     table2 ON table1.user_id = table2.user_id
JOIN     table3 ON table2.partner_id = table3.id
GROUP BY table1.first_name,
         table1.last_name,
         table2.copmany_name,
         (CASE WHEN CONCAT(table1.first_name, table1.last_name) = '' 
               THEN table2.company_name 
               ELSE CONCAT_WS(' ', table1.first_name, table1.last_name) 
          END) AS name