如何从Postges中的Jsonb字段查询SelectJSONArray

如何从Postges中的Jsonb字段查询SelectJSONArray,json,postgresql,postgresql-12,Json,Postgresql,Postgresql 12,我有个问题需要你的帮助。我想按id从JsonArray查询select数据 表(产品) 字段数据包含JsonArray,如下所示 我的问题 预期产量 但查询结果显示字段“data”上包含的所有记录 这和我喜欢的不相配。我只需要id=1的数据,这可以通过使用jsonb\u path\u query\u array()来完成 但这并不完全是您的图片显示的内容:它将不包括“item”键: [{"id": 1, "name": "hawai&quo

我有个问题需要你的帮助。我想按id从JsonArray查询select数据

  • 表(产品)


  • 字段数据包含JsonArray,如下所示
  • 我的问题
  • 预期产量
  • 但查询结果显示字段“data”上包含的所有记录
    这和我喜欢的不相配。我只需要id=1的数据,这可以通过使用
    jsonb\u path\u query\u array()来完成

    但这并不完全是您的图片显示的内容:它将不包括
    “item”
    键:

    [{"id": 1, "name": "hawai", "size": {"L": 0.5, "M": 0.15, "S": 0.25}, "price": 10, "rating": 10}]
    

    这可以使用
    jsonb\u path\u query\u array()来完成。

    但这并不完全是您的图片显示的内容:它将不包括
    “item”
    键:

    [{"id": 1, "name": "hawai", "size": {"L": 0.5, "M": 0.15, "S": 0.25}, "price": 10, "rating": 10}]
    
    试试这个:

      select id, 
             json_build_object('item',array_to_json(array_agg(item))),
             category_id 
    from (
    select id, jsonb_array_elements(data->'item') as "item", category_id 
    from example ) tab
    where cast(item->>'id' as int)=1
    group by id,category_id 
    
    试试这个:

      select id, 
             json_build_object('item',array_to_json(array_agg(item))),
             category_id 
    from (
    select id, jsonb_array_elements(data->'item') as "item", category_id 
    from example ) tab
    where cast(item->>'id' as int)=1
    group by id,category_id 
    

    您是否可以(通过单击下面的链接)询问您的问题,并根据您的样本数据添加预期输出?我不清楚是要提取匹配的数组元素,还是要获取包含一个数组元素的整行matches@a_horse_with_no_name对不起,我标记了错误的版本。目前我正在使用PostgreSQL 12。与此问题相关,您知道我如何通过id选择此项。Thank@a_horse_with_no_name现在,我已经更新了我的问题并链接了我的预期输出结果。你能不能请你的问题(通过点击下面的链接)并根据你的样本数据添加预期输出?我不清楚是要提取匹配的数组元素,还是要获取包含一个数组元素的整行matches@a_horse_with_no_name对不起,我标记了错误的版本。目前我正在使用PostgreSQL 12。与此问题相关,您知道我如何通过id选择此项。Thank@a_horse_with_no_name现在我已经更新了我的问题并链接了我的预期输出结果。谢谢:)@a_horse_和你的答案的名称。如果没有id匹配,那么它将返回
    []
    @AkhileshMishra:是的,你还期望什么?如果您编写了一个不匹配的
    where
    子句,那么就不会返回正确的行。如果把它放在clauseThank you:)@a_horse_,你的答案是“no”。如果没有匹配的id,那么它将返回
    []
    @AkhileshMishra:是的,你还期望什么?如果您编写了一个不匹配的
    where
    子句,那么就不会返回正确的行。如果放在where子句中,我们将不会得到任何行
    [{"id": 1, "name": "hawai", "size": {"L": 0.5, "M": 0.15, "S": 0.25}, "price": 10, "rating": 10}]
    
      select id, 
             json_build_object('item',array_to_json(array_agg(item))),
             category_id 
    from (
    select id, jsonb_array_elements(data->'item') as "item", category_id 
    from example ) tab
    where cast(item->>'id' as int)=1
    group by id,category_id