如何检查和选择postgresql jsonb列与某些数组重叠的行

时间:2019-06-12 22:21:14

标签: postgresql

例如,我有一个表,其中包含一个不嵌套的jsonb列,就像[1,2,3]一样,如何选择与某个数组重叠(具有相同元素)的行,如[1,2,6,8,3]

我尝试过

select * from mytable
where TRANSLATE(myjsonb::jsonb::text, '[]','{}')::INT[]  && ARRAY[1,2,6,8,3]
limit 100

但是它不起作用。我对Postgresql还是很陌生。谢谢

1 个答案:

答案 0 :(得分:1)

您可以按以下方式进行判断:

postgres=# select array(select jsonb_array_elements_text('[1, 2, 3]'::jsonb)) as arr;
   arr   
---------
 {1,2,3}
(1 row)

postgres=# select array(select jsonb_array_elements_text('[1, 2, 3]'::jsonb))::int[] && '{1,2,4}'::int[] as bool;
 bool 
------
 t
(1 row)

postgres=# select array(select jsonb_array_elements_text('[1, 2, 3]'::jsonb))::int[] && '{5,6,7}'::int[] as bool;
 bool 
------
 f
(1 row)

更清晰的示例:

postgres=# \d my_jsonb
  Table "public.my_jsonb"
 Column | Type  | Modifiers 
--------+-------+-----------
 data   | jsonb | 

postgres=# select * from my_jsonb ;
      data       
-----------------
 [1, 2, 3]
 [2, 1, 6, 7, 8]
 [2, 1, 2]
 [3, 4, 5]
 [3, 8, 5, 9]
(5 rows)

postgres=# select
    array(select jsonb_array_elements_text(data))::int[] as arr,
    array(select jsonb_array_elements_text(data))::int[] && '{1,2,4}'::int[] as bool 
from 
    my_jsonb;
     arr     | bool 
-------------+------
 {1,2,3}     | t
 {2,1,6,7,8} | t
 {2,1,2}     | t
 {3,4,5}     | t
 {3,8,5,9}   | f
(5 rows)
相关问题