【问题标题】:how to check and select rows where the postgresql jsonb column overlap with certain array如何检查和选择postgresql jsonb列与某些数组重叠的行
【发布时间】:2019-10-27 11:49:37
【问题描述】:

例如,我有一个带有 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 还很陌生。谢谢

【问题讨论】:

  • id--myjsonb\n 1--[1,2]\n 2--[4,5]\n 3--[2,6]\n 它应该返回第 1 行和第3行

标签: postgresql


【解决方案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)

【讨论】:

  • 但它会将每一行的 jsonb 全部连接到一个数组中并与目标数组重叠......我如何将每一行的 jsonb 与目标数组重叠?
  • 不,它不会将它们全部连接在一起,它只会得到每一行的重叠。看看我上面的新例子。 @qqxlafk
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-20
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 2022-01-18
  • 2012-05-31
相关资源
最近更新 更多