【问题标题】:Postgresql & jsonb : WHERE <a specific nested field in my json> IS NOT NULLPostgresql & jsonb : WHERE <a specific nested field in my json> IS NOT NULL
【发布时间】:2021-09-02 00:51:47
【问题描述】:

public.challenge,列lines JSONB

我在lines 中的初始 JSON :

[
  {
    "line": 1,
    "blocs": [
      {
        "size": 100,
        "name": "abc"
      },
      {
        "size": 100,
        "name": "def"
      },
      {
        "size": 100,
        "name": "ghi"
      }
    ]
  },
  {
    "line": 2,
    "blocs": [
      {
        "size": 100,
        "name": "xyz"
      }
    ]
  }
]

期望的结果(为每个 bloc 添加一个新对象 wrapper):

[
  {
    "line": 1,
    "blocs": [
      {
        "size": 100,
        "name": "abc",
        "wrapper": {
          "nestedName": "abc",
          "type": "regular"
        }
      },
      {
        "size": 100,
        "name": "def",
        "wrapper": {
          "nestedName": "def",
          "type": "regular"
        }
      },
      {
        "size": 100,
        "name": "ghi",
        "wrapper": {
          "nestedName": "ghi",
          "type": "regular"
        }
      }
    ]
  },
  {
    "line": 2,
    "blocs": [
      {
        "size": 100,
        "name": "xyz",
        "wrapper": {
          "nestedName": "xyz",
          "type": "regular"
        }
      }
    ]
  }
]

我有以下查询(来自here):

WITH cte AS (
   SELECT id_lines,
          jsonb_agg(
                  jsonb_set(val1, '{blocs}',
                      (
                        SELECT jsonb_agg(arr2 ||
                                         json_build_object(
                                             'wrapper', json_build_object('nestedName', arr2->'name', 'type', 'regular')
                                             )::jsonb
                            )
                        FROM jsonb_array_elements(arr1.val1->'blocs') arr2
                        WHERE arr2->'name' IS NOT NULL
                          )
                      ))
   FROM public.challenge, jsonb_array_elements(lines) arr1(val1)
   GROUP BY 1
)
UPDATE public.challenge SET lines=(cte.jsonb_agg) FROM cte
WHERE public.challenge.id_lines=cte.id_lines;

条件WHERE arr2-&gt;'name' IS NOT NULL 没有过滤掉名称为空的块,我很难找出原因......谢谢!

【问题讨论】:

    标签: postgresql sql-update jsonb


    【解决方案1】:

    你必须区分 SQL NULL 和 JSON null

    IS NOT NULL 谓词测试 SQL NULL,这意味着 JSON 中不存在该属性。

    要测试 JSON null,请使用

    WHERE arr2->'name' <> 'null'::jsonb
    

    类型转换为jsonb 不是必需的,会隐式执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 2020-04-22
      • 1970-01-01
      • 2021-11-29
      • 2015-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多