Sql 如何在postgres中将数组元素从字符串转换为int?

Sql 如何在postgres中将数组元素从字符串转换为int?,sql,postgresql,jsonb,Sql,Postgresql,Jsonb,表中有一列是jsonb[14,21,31] 我想得到所有包含所选元素的行 SELECT * FROM t_customers WHERE tags ?| array['21','14'] 但是jsonb元素是整数格式的 如何将sql数组元素转换为整数 我尝试从数组中删除引号,但出现了一个错误简单的解决方案是: t=# with t_customers(tags) as (values('[14,21,31]'::jsonb)) select tags , translate(tags:

表中有一列是jsonb
[14,21,31]
我想得到所有包含所选元素的行

SELECT * 
FROM t_customers 
WHERE tags ?| array['21','14']
但是jsonb元素是整数格式的 如何将sql数组元素转换为整数
我尝试从数组中删除引号,但出现了一个错误

简单的解决方案是:

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)
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转换为数组并检查它是否包含,但现在可能这种天真的方法是最短的)

正确的方法可能是:

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)
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数组

@LaurenzAlbe:但不能使用
int[]
作为
运算符的右边值-这需要
text[]
如果将这些整数存储在
int[]中,会更容易(可能更高效)
column而不是
jsonb
是否有其他运算符可以替代?|将int[]@a_horse_与_no_name与JSON数组匹配。正如我所说:这最好存储在原生Postgres数组中