簡體   English   中英

在 Postgres 中查詢 JSON 數組

[英]Querying a JSON array in Postgres

我有一張帶有 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") 的行?

您在問題規范中使用“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'

添加 integer 值的條件有點復雜,因為? 運算符僅適用於字符串。 所以你需要取消嵌套數組:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM