将多行合并为单行PostgreSQL

时间:2017-09-10 17:32:50

标签: postgresql join merge

我有一个名为deliveries的主表,它与deliveries_languages有一对多关系,如dl,deliveries_markets dm和deliveries_tags dt,其delivery_id为外键。这3个表分别与语言,市场和标签有一对一的关系。另外,交付,表与公司有一对一的关系,并将company_is作为外键。以下是我写的一个查询:

SELECT deliveries.*, languages.display_name, markets.default_name, tags.default_name, companies.name
FROM deliveries
JOIN deliveries_languages dl ON dl.delivery_id = deliveries.id 
JOIN deliveries_markets dm ON dm.delivery_id = deliveries.id 
JOIN deliveries_tags dt ON dt.delivery_id = deliveries.id 
JOIN languages ON languages.id = dl.language_id 
JOIN markets ON markets.id = dm.market_id 
JOIN tags ON tags.id = dt.tag_id 
JOIN companies ON companies.id = deliveries.company_id 
WHERE 
deliveries.name ILIKE '%new%' AND 
deliveries.created_by = '5f331347-fb58-4f63-bcf0-702f132f97c5' AND 
deliveries.deleted_at IS NULL 
LIMIT 10

这里我得到了冗余的delivery_ids,因为每个delivery_id都有多种语言,市场和标签。我想对不同的delivery_ids使用限制,同时,我希望将这些多种语言,市场和标签分组并填充到单行中。

目前它看起来像:

delivery_id | name |languages | markets  | tags
------------|------|----------|----------|-----------
1           | d1   |en        | au       | tag1
1           | d1   |de        | sw       | tag2
2           | d2   |en        | au       | tag1
2           | d2   |de        | sw       | tag2
3           | d3   |en        | au       | tag1
3           | d3   |de        | sw       | tag2

我可以通过以下任何方式获得数据:

delivery_id | name |languages | markets  | tags
------------|------|----------|----------|-----------
1           | d1   |en, de    | au,sw    | tag1, tag2
2           | d2   |en, de    | au,sw    | tag1, tag2
3           | d3   |en, de    | au,sw    | tag2, tag3

P.S。上面的表只包含部分数据,实际查询返回的列数多,但上面的列很重要。有人可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

您可以GROUP BY使用string_agg,如下所示:

SELECT deliveries.deliver_id, deliver.name, 
       string_agg(distinct languages.display_name, ',' order by languages.display_name) as langs, 
       string_agg(distinct markets.default_name, ',' order by markets.default_name) as markets,
       string_agg(distinct tags.default_name, ',' order by tags.default_name) as tags,
       string_agg(distinct companies.name, ',' order by companies.name) as companies
    ...
    GROUP BY deliveries.deliver_id, deliver.name;