【问题标题】:Postgresql put strings inside quotes with array_to_stringPostgresql 用 array_to_string 将字符串放在引号内
【发布时间】:2018-04-25 10:42:51
【问题描述】:

在选择中我使用了这样的array_to_string(示例)

array_to_string(array_agg(tag_name),';') tag_names

我得到了结果字符串"tag1;tag2;tag3;...",但我想得到结果字符串"'tag1';'tag2';'tag3';..."

如何在 Postgres 中做到这一点?

【问题讨论】:

  • array_to_string(array_agg(...)) 可以简化为string_agg()
  • @a_horse_with_no_name 谢谢:)

标签: arrays postgresql string-aggregation


【解决方案1】:

使用string_agg()format() 函数,例如

with my_table(tag_name) as (
values 
    ('tag1'),
    ('tag2'),
    ('tag3')
)

select string_agg(format('''%s''', tag_name), ';' order by tag_name) tag_names
from my_table;

      tag_names       
----------------------
 'tag1';'tag2';'tag3'
(1 row)

【讨论】:

    【解决方案2】:

    或者您可以在这样的一个请求中使用unnestformatarray_aggarray_to_string

    select array_to_string(t.tag, ',')  
    from (  
        select array_agg(format('%L', t.tag)) as tag  
        from (  
            select unnest(tag_name) as tag  
        ) t  
    ) t;
    

    【讨论】:

      【解决方案3】:

      或者使用

      array_to_string(array_agg(''''||tag_name||''''),';') tag_names 
      

      甚至更简单(感谢您的评论:))

      string_agg(''''||tag_name||''''),';') tag_names 
      

      注意:

      在处理多参数聚合函数时,请注意 ORDER BY 子句在所有聚合参数之后。例如, 写这个:

      SELECT string_agg(a, ',' ORDER BY a) FROM table;

      不是这个:

      SELECT string_agg(a ORDER BY a, ',') FROM table; -- 不正确

      https://www.postgresql.org/docs/current/static/sql-expressions.html#SYNTAX-AGGREGATES

      【讨论】:

      • 这里的替代应该是字符串连接,你应该仍然使用 string_agg 而不是 array_to_string(array_agg())
      • @eurotrash 谢谢:)!
      【解决方案4】:

      您可以将string_agg() 函数与'''; ''' 一起使用,这样就可以了

      SELECT string_agg(tag_name, '''; ''') from my_table
      

      【讨论】:

        猜你喜欢
        • 2021-11-21
        • 2012-03-05
        • 2018-05-06
        • 2016-08-29
        • 1970-01-01
        • 1970-01-01
        • 2018-03-17
        • 1970-01-01
        • 2017-07-31
        相关资源
        最近更新 更多