[英]Fetching Value from Json Array Object in Postgres
I'm new to Postgres so I'm stuck while creating a query. 我是Postgres的新手,所以在创建查询时遇到了麻烦。
The table definition: 表定义:
id - primary key,
data - JSON
Sample data: 样本数据:
id data
--------------------------------------------------------------
1 [{"279863":"500040004","awb_no":"18171917033930"},{"279864":"500040003","awb_no":"18171917033931"}]
I want to find the key (279864) exists in my data column using where clause 我想使用where子句在我的数据列中找到键(279864)存在
t=# with c(id,data) as (values(1,'[{"279863":"500040004","awb_no":"18171917033930"},{"279864":"500040003","awb_no":"18171917033931"}]'::json))
select id,json_object_keys(json_array_elements(data)) = '279864' from c;
id | ?column?
----+----------
1 | f
1 | f
1 | t
1 | f
(4 rows)
so you can check with WHERE EXISTS
or count(*) > 0
or any another way you like... 因此您可以使用
WHERE EXISTS
或count(*) > 0
或您喜欢的任何其他方式进行检查...
eg, with bool_or
(if at least one is true, group is true): 例如, 使用
bool_or
(如果至少一个为true,则group为true):
t=# with c(id,data) as (values(1,'[{"279863":"500040004","awb_no":"18171917033930"},{"279864":"500040003","awb_no":"18171917033931"}]'::json))
, m as (select id,(json_object_keys(json_array_elements(data)) = '279864')j from c)
select id, bool_or(j) from m group by id;
id | bool_or
----+---------
1 | t
(1 row)
So in short: 简而言之:
json_array_elements
to divide array for check. json_array_elements
划分数组进行检查。 json_object_keys
toget the key of divided array element json_object_keys
分割数组元素的键 update as OP is asking for "less complicated" solution, I post a monkey hack as well: 更新为OP是要求“不太复杂”的解决方案,我发布一个猴子入侵,以及:
t=# with c(id,data) as (values(1,'[{"279863":"500040004","awb_no":"18171917033930"},{"279864":"500040003","awb_no":"18171917033931"}]'::json))
select * from c where data::jsonb::text ~ '(,)|({ )"279863":';
id | data
----+-----------------------------------------------------------------------------------------------------
1 | [{"279863":"500040004","awb_no":"18171917033930"},{"279864":"500040003","awb_no":"18171917033931"}]
(1 row)
which is of course is very slippery and requires some explanation as well: 这当然很滑,也需要一些解释:
jsonb
first to eliminate possible syntax freedom jsonb
以消除可能的语法自由 {
{ and ,
cases {
{和,
案件 将数据列设置为JSONB
,然后可以使用以下命令轻松完成操作:
SELECT * FROM table WHERE data->>'279863' IS NOT NULL;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.