【问题标题】:Put strings inside quotes with string_to_array()使用 string_to_array() 将字符串放在引号内
【发布时间】:2021-11-21 21:52:39
【问题描述】:

我正在使用以下查询:

WITH a as (SELECT unnest(string_to_array(animals, ',')) as "pets" FROM all_animals where id = 100)
select * from a

返回以下数据:

1 Cat
2 Dog
3 Bird

我的问题是,如何格式化我上面的 string_to_array 选择以包含返回数据的单引号,如下所示:

1 'Cat'
2 'Dog'
3 'Bird'

【问题讨论】:

    标签: sql postgresql quotes string-agg


    【解决方案1】:

    使用quote_literal() 安全地单引号字符串:

    WITH a AS (
       SELECT unnest(string_to_array(animals, ',')) AS pets
       FROM   all_animals
       WHERE  id = 100
       )
    SELECT quote_literal(pets) AS pets
    FROM   a;
    

    没有 CTE 或者更短:

    SELECT quote_literal(unnest(string_to_array(animals, ','))) AS pets
    FROM   all_animals
    WHERE  id = 100;
    

    db小提琴here

    【讨论】:

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