在 Postgres 中查询 JSONB 中的复杂数组

Query complicated array in a JSONB in Postgres

我有一个 JSONB 字段值:

{
   "status":200,
   "response":{
      "page":1,
      "limit":10,
      "total":4,
      "orders":[
         {
            "id":40201
         },
         {
            "id":40111
         }
      ]
   }
}

如何查询 id=40201 的订单数组对象?

我正在尝试查询具有 response->orders->[id: 40201] 的所有行

demo:db<>fiddle

如果您知道这是数组中的第一个对象 (zero-based!):

SELECT
    yourjson -> 'response' -> 'orders' -> 0

如果不是,则必须使用 jsonb_array_elements() 将数组扩展为每个元素一行并过滤每一行:

SELECT 
    elems.value
FROM 
    yourtable,
    jsonb_array_elements(yourjson -> 'response' -> 'orders') elems
WHERE
    elems ->> 'id' = '40201'

documentation

我会为此使用 exists 查询:

select *
from the_table
where exists (select *
              from jsonb_array_elements(the_json_column -> 'response' -> 'orders') as x (o)
              where x.o ->> 'id' = 40201');

或者使用 @> 包含运算符:

select *
from the_table
where exists (select *
              from jsonb_array_elements(the_json_column -> 'response' -> 'orders') as x (o)
              where x.o @> '{"id" : 40201}';