我是Postgres的新手,所以我在创建查询时遇到困难。
表格定义:
id - primary key,
data - JSON
示例数据:
id data
--------------------------------------------------------------
1 [{"279863":"500040004","awb_no":"18171917033930"},{"279864":"500040003","awb_no":"18171917033931"}]
我想使用where子句
找到我的数据列中存在的密钥(279864)答案 0 :(得分:1)
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)
因此您可以使用WHERE EXISTS
或count(*) > 0
或您喜欢的任何其他方式查看...
例如,with bool_or
(如果至少有一个为真,则组为真):
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)
简而言之:
json_array_elements
来划分数组以进行检查。json_object_keys
来获取分割数组元素的键更新,因为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)
当然非常滑,也需要一些解释:
jsonb
以消除可能的语法自由{
{和,
个案例答案 1 :(得分:0)
将数据列设为JSONB
,然后您可以使用以下方法轻松完成:
SELECT * FROM table WHERE data->>'279863' IS NOT NULL;