我有一个带有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”)的行?
检查国家/地区非常简单,因为这是一个文本值:
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'));
您在问题说明中对“ in”的使用令人困惑,因为您似乎正在以类似SQL的伪语法来使用它,但含义与SQL不相同。
[如果要在其中一个国家是美国并且11和12都包含在“ interestedIn”中的行,则可以在一个包含操作中完成:
select * from orders where info::jsonb @> '{"interestedIn":[11,12],"countries":["US"]}'
如果您还需要其他内容,请更详细地说明,并提供应匹配的示例和不匹配的示例(并告诉我们哪个是哪个。)