在对象数组中的属性值中选择行,多个值之一

发布于 2025-01-23 04:02:46 字数 747 浏览 0 评论 0原文

我的数据如下:Postgres

ID数据
1[{“ A”:3,“ B”:“ green”} 的JSONB列中的对象数组}]
2[{{“ a”:3,“ b”:“ red”},{“ a”:5,“ b”:“ yellow”}]
3[{“ a”:3,“ b”:“” {”

橙色“} , 代码>“黄色”

我知道我可以使用JSONB_ARRAY_ELEMENTS获取所有b值,

select jsonb_array_elements(data) ->> 'b' from table

但我未能在此处查询中使用该数据此

 select * from table where jsonb_array_elements(data) ->> 'b' && ARRAY["green","yellow"]::varchar[] 

(不允许在哪里允许使用“集合返回功能”)

I have data shaped like this: arrays of objects in a jsonb column in postgres

iddata
1[{"a":3, "b":"green"} ,{"a":5, "b":"blue"}]
2[{"a":3, "b":"red"} ,{"a":5, "b":"yellow"}]
3[{"a":3, "b":"orange"} ,{"a":5, "b":"blue"}]

I am trying to select the rows where b is either "green" or "yellow"

I know I can unroll the data using jsonb_array_elements to get all the b values

select jsonb_array_elements(data) ->> 'b' from table

but I am failing to use that in a where query like this

 select * from table where jsonb_array_elements(data) ->> 'b' && ARRAY["green","yellow"]::varchar[] 

(not working "set-returning functions are not allowed in WHERE")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

同展鸳鸯锦 2025-01-30 04:02:46

您可以使用@>运算符

select *
from the_table
where data @> '[{"b": "green"}]'
   or data @> '[{"b": "yellow"}]'

或JSON路径表达式:

select *
from the_table
where data @@ '$[*].b == "green" || $[*].b == "yellow"';

或通过不存在存在条件的数组:

select t.*
from the_table t
where exists (select *
              from jsonb_array_elements(t.data) as x(item)
              where x.item ->> 'b' in ('green', 'yellow'))

You can use the @> operator

select *
from the_table
where data @> '[{"b": "green"}]'
   or data @> '[{"b": "yellow"}]'

Or a JSON path expression:

select *
from the_table
where data @@ '$[*].b == "green" || $[*].b == "yellow"';

Or by unnesting the array with an EXISTS condition:

select t.*
from the_table t
where exists (select *
              from jsonb_array_elements(t.data) as x(item)
              where x.item ->> 'b' in ('green', 'yellow'))
你的他你的她 2025-01-30 04:02:46

您可以尝试使用列名称和的子查询,如下

SELECT *
FROM (
  select *,jsonb_array_elements(data) ->> 'b' val 
  from t
) t1
WHERE t1.val = ANY (ARRAY['green','yellow'])

sqlfiddle

note

array滤波器值需要使用单引号而不是双引号

You can try to use subquery with a column alias name and ANY like below

SELECT *
FROM (
  select *,jsonb_array_elements(data) ->> 'b' val 
  from t
) t1
WHERE t1.val = ANY (ARRAY['green','yellow'])

sqlfiddle

NOTE

ARRAY filter value need to use single quote instead of double quote

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文