检查json是否包含postgres中的值

问题描述 投票:0回答:2

从我的数据库中,我形成了一个json数据,如下所示。我正在尝试在json数据中搜索值

[
  {"fc_primary_key": "A1234567892017/06/27"},
  {"fc_primary_key": "A1234567892017/06/27"},
  {"fc_primary_key": "A1234567892017/08/07"},
  {"fc_primary_key": "A1234567892017/08/07"},
  {"fc_primary_key": "A1234567892017/08/07"},
  {"fc_primary_key": "A1234567892017/08/07"},
  {"fc_primary_key": "A1234567892017/08/07"},
  {"fc_primary_key": "A1234567892024/03/01"},
  {"fc_primary_key": "A12345678945353"},
  {"fc_primary_key": "A1234567892023/11/22"},
  {"fc_primary_key": "A12345678945252"},
  {"fc_primary_key": "A1234567892017-07-01"}
]

在以上数据中,我试图查找其中是否有A1234567892023/11/22

我已经尝试了以下查询,但它给了我错误。

select 'A1234567892023/11/22'=ANY(json_array_elements_text(fpo_data));

请帮助。

postgresql postgresql-9.3 postgresql-9.4 postgresql-9.5
2个回答
1
投票

您需要取消嵌套数组:

select t.*
from the_table t
where exists (select *
              from json_array_elements_text(t.fpo_data) as x(ky, val)
              where x.val = 'A1234567892023/11/22')

使用Postgres 12,可以简化为

select t.*
from the_table t
where jsonb_path_exists(t.fpo_data, '$.[*] ? (@.fc_primary_key == "A1234567892023/11/22")')

1
投票

最简单的方法是使用jsonb包含运算符:

WHERE fpo_data @> JSONB '[{"fc_primary_key": "A1234567892023/11/22"}]'
© www.soinside.com 2019 - 2024. All rights reserved.