如何查询 JSONB 数组
How To Query an array of JSONB
我有 table(订单),其中 jsonb[]
列在 Postgres 数据库中名为 steps
。
我需要创建 SQL 查询到 select 记录,其中 Step1 和 Step2 和 Step3 具有 成功状态
[
{
"step_name"=>"Step1",
"status"=>"success",
"timestamp"=>1636120240
},
{
"step_name"=>"Step2",
"status"=>"success",
"timestamp"=>1636120275
},
{
"step_name"=>"Step3",
"status"=>"success",
"timestamp"=>1636120279
},
{
"step_name"=>"Step4",
"timestamp"=>1636120236
"status"=>"success"
}
]
table结构
编号 |姓名 |步骤 (jsonb)
您可以使用JSON值包含操作来检查条件是否存在
select
*
from
test
where
steps @> '[{"step_name":"Step1","status":"success"},{"step_name":"Step2","status":"success"},{"step_name":"Step3","status":"success"}]'
'Normalize' steps
到 JSON 项的列表中,并检查是否每个项都有 "status":"success"
。顺便说一句,您的示例无效 [=18=]。所有 =>
都需要替换为 :
并且缺少一个逗号。
select id, name from orders
where
(
select bool_and(j->>'status' = 'success')
from jsonb_array_elements(steps) j
where j->>'step_name' in ('Step1','Step2','Step3') -- if not all steps but only these are needed
);
我有 table(订单),其中 jsonb[]
列在 Postgres 数据库中名为 steps
。
我需要创建 SQL 查询到 select 记录,其中 Step1 和 Step2 和 Step3 具有 成功状态
[
{
"step_name"=>"Step1",
"status"=>"success",
"timestamp"=>1636120240
},
{
"step_name"=>"Step2",
"status"=>"success",
"timestamp"=>1636120275
},
{
"step_name"=>"Step3",
"status"=>"success",
"timestamp"=>1636120279
},
{
"step_name"=>"Step4",
"timestamp"=>1636120236
"status"=>"success"
}
]
table结构 编号 |姓名 |步骤 (jsonb)
您可以使用JSON值包含操作来检查条件是否存在
select
*
from
test
where
steps @> '[{"step_name":"Step1","status":"success"},{"step_name":"Step2","status":"success"},{"step_name":"Step3","status":"success"}]'
'Normalize' steps
到 JSON 项的列表中,并检查是否每个项都有 "status":"success"
。顺便说一句,您的示例无效 [=18=]。所有 =>
都需要替换为 :
并且缺少一个逗号。
select id, name from orders
where
(
select bool_and(j->>'status' = 'success')
from jsonb_array_elements(steps) j
where j->>'step_name' in ('Step1','Step2','Step3') -- if not all steps but only these are needed
);