在postgres中等效的GROUP_CONCAT()

时间:2019-10-17 06:47:43

标签: sql postgresql string-aggregation

在MySQL中,我使用GROUP_CONCAT()函数,但是现在我需要将其转换为Postgres。谁能帮我把这种查询转换成Postgres吗?我认为唯一需要替换的是带有GROUP_CONCAT的行?

SET @sql = NULL;
SELECT CONCAT(
   'SELECT ',GROUP_CONCAT(c.TABLE_NAME,'.',c.COLUMN_NAME,' AS `',c.TABLE_NAME,'.',c.COLUMN_NAME,'`'),'
    from t1 AS thre
inner join t2 as ter on thre.datasource = ter.datasource 
inner join t3 as ston on thre.datasource = ston.datasource
inner join t4 as diron on thre.datasource = diron.datasource'
)
INTO @sql
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE c.TABLE_NAME IN ('t1','t2',
                       't3','t4');    
PREPARE sql_statement FROM @sql;
EXECUTE sql_statement;

2 个答案:

答案 0 :(得分:0)

您可以使用STRING_AGG

select 'SELECT '||string_agg(c.TABLE_NAME||'.'||c.COLUMN_NAME||' AS '
                           ||c.TABLE_NAME||'.'||c.COLUMN_NAME ,',') ||
            'from t1 AS thre inner join t2 ..
            ..
            .. = diron.datasource'              
 from INFORMATION_SCHEMA.COLUMNS c 

||是Postgres中的串联运算符

答案 1 :(得分:0)

我认为您正在寻找string_agg()函数

https://www.postgresql.org/docs/12/functions-aggregate.html