【问题标题】:how to convert array elements from string to int in postgres?如何在postgres中将数组元素从字符串转换为int?
【发布时间】:2018-05-23 07:34:16
【问题描述】:

我在表中有一个列 jsonb [14,21,31] 我想获取所有带有选定元素的行,例如

SELECT * 
FROM t_customers 
WHERE tags ?| array['21','14']

但是 jsonb 元素是整数格式 我如何将sql数组元素转换为整数 我尝试从数组中删除引号,但它给出了错误

【问题讨论】:

  • @LaurenzAlbe: 但您不能使用 int[] 作为 ?| 运算符的右手值 - 这需要 text[]
  • 如果将这些整数存储在int[] 列而不是jsonb 列中会容易得多(并且可能更有效)
  • 我可以使用其他运算符来代替吗?|匹配 int[] @a_horse_with_no_name
  • 不适用于 JSON 数组。正如我所说:这最好存储在本机 Postgres 数组中

标签: sql postgresql jsonb


【解决方案1】:

一个天真的解决方案是:

t=# with t_customers(tags) as (values('[14,21,31]'::jsonb))
select
  tags
, translate(tags::text,'[]','{}')::int[] jsonb_int_to_arr
, translate(tags::text,'[]','{}')::int[] @> array['21','14']::int[] includes
from
t_customers;
     tags     | jsonb_int_to_arr | includes
--------------+------------------+----------
 [14, 21, 31] | {14,21,31}       | t
(1 row)

https://www.postgresql.org/docs/current/static/functions-array.html 如果你想转换为数组 - 你应该使用@> 运算符来检查是否包含。

(起初我提出它是因为我误解了这个问题 - 所以它采取了相反的方式,将 jsonb 转换为数组并检查它是否包含,但现在这种幼稚的方法可能是最短的)

这里的正确方法可能是:

t=# with t_customers(tags) as (values('[14,21,31]'::jsonb))
, t as (select tags,jsonb_array_elements(tags) from t_customers)
select jsonb_agg(jsonb_array_elements::text) ?| array['21','14'] tags from t group by tags;
 tags
------
 t
(1 row)

这基本上是用整数的文本表示“重新打包”jsonb数组

【讨论】:

    猜你喜欢
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 2018-05-31
    • 2011-01-09
    • 2018-05-29
    相关资源
    最近更新 更多