[英]Query for array values within jsonb column
I have a jsonb
column called chores
in my work
table with data looking something like this:我的
work
表中有一个名为chores
的jsonb
列,其中的数据如下所示:
[{"task": "feed_dog", "value": "Daily"},{"task": "mop_floor", "value": "Weekly"]
There could be zero to dozens of tasks in the chores
array for each user.每个用户的
chores
数组中可能有零到几十个任务。
How can I query by task name?如何按任务名称查询? For example, pull all records where at least one
task
is feed_dog
.例如,提取至少一项
task
为feed_dog
的所有记录。
SELECT chores->>'task' FROM work
returns a bunch of null
results, as does SELECT chores->'task' FROM work
. SELECT chores->>'task' FROM work
返回一堆null
结果, SELECT chores->'task' FROM work
也是如此。
You need to unnest the array:您需要取消嵌套数组:
select w.*
from "work" w
where exists (select *
from jsonb_array_elements(w.chores) as t(task)
where t.task ->> 'task" = 'feed_dog');
With Postgres 12 this is a bit easier to write:使用 Postgres 12,这更容易编写:
select *
from "work" w
where jsonb_path_exists(w.chores, '$[*] ? (@.task == "feed_dog")')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.