【问题标题】:Where condition on list of jsonb in PostgresPostgres中jsonb列表的条件
【发布时间】:2021-12-14 10:58:35
【问题描述】:

假设我有表 food_articles,它有以下列:name(type ="text") 和 ingredients(type="jsonb[]"),其中成分 jsonb 对象看起来像这个:

{
    ingredient_id: 'string',
    quantity: 'number'
} 

如何创建一个查询来返回 food_articles 中所有在成分 jsonb 数组中包含 ingredient_id = 1337 的行?

【问题讨论】:

    标签: sql arrays postgresql jsonb


    【解决方案1】:

    where 子句中将ingredients 嵌套到表中,并检查是否存在ingredient_id = '1337' 的记录。

    select * from food_articles 
    where exists
    (
     select 
     from unnest(ingredients) arj 
     where arj ->> 'ingredient_id' = '1337' 
    );
    

    请注意,如果 ingredients 的类型是 jsonb,它包含一个类似 '[{"ingredient_id":"1337","quantity":1},{"ingredient_id":"1336","quantity":2}]' 的数组,而不是包含 jsonb 元素的 Postgres 数组(即 jsonb[]),那么您可以使用“包含”@>运算符简单地作为

    where ingredients @> '[{"ingredient_id":"1337"}]'
    

    【讨论】:

    • 您建议的第一个代码 sn-p 有效!但是,使用 @> 运算符不起作用,它说:“详细信息:“[”必须引入明确指定的数组维度。”即使该列的类型为 jsonb[]
    • 是的,它需要jsonb,而不是jsonb[] 列。
    【解决方案2】:
    create table "food_articles" ("name" text, "ingredients" jsonb);
    
    insert into "food_articles" values('food 1', jsonb_build_object('ingredient_id', 1, 'quantity', 1)),
     ('food 2', jsonb_build_object('ingredient_id',2, 'quantity',1337)),
    ('food 3', jsonb_build_object('ingredient_id',3, 'quantity',1337)),
    ('food 3', jsonb_build_object('ingredient_id', 3, 'quantity',1332));
    
    select * from "food_articles"
    where "ingredients"->>'quantity'='1337';
    

    游乐场链接:https://dbfiddle.uk/?rdbms=postgres_13&fiddle=b6ab520a44c65656ebc767a10f5737b6

    postgresql jsonb 操作的文档:https://www.postgresql.org/docs/9.5/functions-json.html

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多