简体   繁体   English

在 Postgres 中查询 JSON 数组

[英]Querying a JSON array in Postgres

I have a table with json field我有一张带有 json 字段的表

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

I inserted data to it我向其中插入了数据

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

How can I get rows where intrestedIn in(11, 12) and countries in("US")?如何获得intrestedIn in(11, 12) 和countries in("US") 的行?

Your use of "in" in the problem specification is confusing, as you seem to be using it in some SQL-like pseudo syntax, but not with the same meaning it has SQL.您在问题规范中使用“in”令人困惑,因为您似乎在一些类似 SQL 的伪语法中使用它,但与 SQL 的含义不同。

If you want rows where one of the countries is US and where both 11 and 12 are contained in "interestedIn", then it can be done in a single containment operation:如果您想要其中一个国家是美国并且 11 和 12 都包含在“interestedIn”中的行,那么可以在单个包含操作中完成:

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

If you want something other than that, then please explain in more detail, and provide both examples which should match and examples which should not match (and tell us which is which).如果您想要除此之外的其他内容,请更详细地解释,并提供应该匹配的示例和不应该匹配的示例(并告诉我们哪个是哪个)。

Checking for the country is quite simple as that is a text value:检查国家非常简单,因为这是一个文本值:

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

Adding the condition for the integer value is a bit more complicated because the ?添加 integer 值的条件有点复杂,因为? operator only works with strings.运算符仅适用于字符串。 So you need to unnest the array:所以你需要取消嵌套数组:

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'));

If you also might need to check for multiple country values, you can use the ?|如果您还可能需要检查多个国家/地区的值,您可以使用?| operator:操作员:

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'));

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM