mysql JSON_SET 或 JSON_INSERT 函数将对象插入嵌套对象(如果存在)

mysql JSON_SET or JSON_INSERT function to insert object into nested object if it exists

我有一个 json 类型的列 config 我想添加一个键值对,最终看起来像:

{
  "features": {
    "divisions": true,
    "utilities": {
        "water": true,
        "gas": true,
        "electric": true
    }
  }
}

我 运行 遇到的问题是,当我想在功能中插入实用程序对象时,我要么覆盖 divisions 键值,要么返回 NULL utilities 对象未被插入。

此外,config 列可能是 NULL 或最初只是一个空的 {}

此查询将检查 NULL 或空 {} 以及 features 键是否存在,但会导致覆盖 features 如果它已经存在:

UPDATE entities SET config = JSON_SET(COALESCE(config, '{}'),
  COALESCE("$.features", "features"), JSON_OBJECT("utilities", 
  JSON_OBJECT("water", TRUE, "gas", TRUE, "electric", TRUE))) 
  WHERE id = 123725082;

这工作正常,除非该列已经包含如下内容:

{
  "features": {
    "divisions": true,
  }
}

其中它用 utilities 对象覆盖 divisions

所以我正在尝试 JSON_INSERT 查询;从我从 mysql json 函数文档中收集到的内容应该可以工作,但它返回 null,我不明白为什么:

UPDATE entities SET config = JSON_INSERT(COALESCE(config, '{}'),
  COALESCE("$.features", "features"), JSON_OBJECT("utilities", 
  JSON_OBJECT("water", TRUE, "gas", TRUE, "electric", TRUE))) 
  WHERE id = 123725082;

JSON_MERGE 函数在这种情况下很有用。

根据需要修改UPDATE

UPDATE `entities`
  SET `config` = COALESCE(
    JSON_MERGE(
      `config`,
      JSON_OBJECT('features',
        JSON_OBJECT('utilities',
          JSON_OBJECT('water', TRUE, 'gas', TRUE, 'electric', TRUE)
        )
      )
    ),
    JSON_INSERT(
      JSON_OBJECT(),
      '$.features',
       JSON_OBJECT('utilities',
         JSON_OBJECT('water', TRUE, 'gas', TRUE, 'electric', TRUE)
       )
    )
  );

db-fiddle