在Postgres中查询JSON数组

我有一个带有json字段的表

CREATE TABLE orders (
                      ID serial NOT NULL PRIMARY KEY,info json NOT NULL
);

我向其中插入了数据

INSERT INTO orders (info)
VALUES
(
  '{"interestedIn":[11,12,13],"countries":["US","UK"]}'
);

如何获取intrestedIn in(11,12)和countries in(“ US”)中的行?

yang01104891 回答:在Postgres中查询JSON数组

您在问题说明中使用“ in”令人困惑,因为您似乎在以某种类似于SQL的伪语法使用它,但含义与SQL并不相同。

如果要在其中一个国家是美国且11和12都包含在“ interestedIn”中的行,则可以通过单个包含操作来完成:

select * from orders where info::jsonb @> '{"interestedIn":[11,12],"countries":["US"]}'

如果您还需要其他内容,请进行详细说明,并提供应匹配的示例和不匹配的示例(并告诉我们哪个是哪个)。

,

检查国家/地区非常简单,因为这是一个文本值:

select *
from orders
where info::jsonb -> 'countries' ? 'US'

为整数值添加条件要复杂一点,因为?运算符仅适用于字符串。所以您需要取消嵌套数组:

select o.*
from orders o
where o.info::Jsonb -> 'countries' ? 'US'
  and exists (select *
              from json_array_elements_text(o.info -> 'interestedIn') as x(id)
              where x.id in ('11','12'));

如果您可能还需要检查多个国家/地区值,则可以使用?|运算符:

select o.*
from orders o
where o.info::jsonb -> 'countries' ?| array['US','UK']
  and exists (select *
              from json_array_elements_text(o.info -> 'interestedIn') as x(id)
              where x.id in ('11','12'));

在线示例:https://rextester.com/GSDTOH43863

本文链接:https://www.f2er.com/3066990.html

大家都在问