【问题标题】:MYSQL - edit JSON object that is in array of json objectMYSQL - 编辑 json 对象数组中的 JSON 对象
【发布时间】:2020-09-12 13:48:59
【问题描述】:

表名

guilds

数据

members = {
    'look': [{
        id: '123',
        bot: false,
        username: 'Joe',
    }, {
        id: '456',
        bot: false,
        username: 'Jeff',
    }]
};

'look' 包含一堆 json 对象。 'members' 是表 'guilds' 中一行的名称。 我的目标是将 ID 为“123”的用户名编辑为 Janet。

将 MYSQL 8.0 与 JavaScript 结合使用。 (使用模块 mysql、Node.js)。

我试过了

我尝试获取成员行,然后解析结果并将新值分配给相应的字段。事实证明 mysql 没有任何功能可以像 mongoose 那样从那里更新它。

connection.query(`SELECT members FROM guilds WHERE id='${_guild_id}'`, (err, result) => {
   let parse = JSON.parse(result[0].members);
   parse.look.forEach(element => {
      if (element.id === '123') {
        element.username = "some name"
      }
   });
});

【问题讨论】:

    标签: mysql sql node.js json sql-update


    【解决方案1】:

    一种选择是使用json_table 将数组完全取消嵌套到列和行中,然后重建对象(这需要您事先知道对象的完整结构)。

    首先,考虑以下select 查询,它解析、修改和重建对象:

    select json_object(
        'look', 
        json_arrayagg(
            json_object(
                'id', j.id, 
                'bot', j.bot, 
                'username', case when j.id = 123 then 'Janett' else j.username end
            )
        )
    ) v
    from guilds g
    cross join json_table(
        g.members ->> '$.look',
        '$[*]'
        columns (
            id int path '$.id',
            bot boolean path '$.bot',
            username varchar(100) path '$.username'
        )
    ) j
    where id = 1
    

    然后,您可以将其转换为 update 查询,如果这是您想要的:

    update guilds g
    inner join (
        select g.id, json_object(
            'look', 
            json_arrayagg(
                json_object(
                    'id', j.id, 
                    'bot', j.bot, 
                    'username', case when j.id = 123 then 'Janett' else j.username end
                )
            )
        ) new_members
        from guilds g
        cross join json_table(
            g.members ->> '$.look',
            '$[*]'
            columns (
                id int path '$.id',
                bot boolean path '$.bot',
                username varchar(100) path '$.username'
            )
        ) j
        where g.id = 1
        group by g.id
    ) x
    on g.id = x.id
    set g.members = x.new_members
    

    【讨论】:

      猜你喜欢
      • 2020-11-28
      • 2021-10-26
      • 2019-11-25
      • 1970-01-01
      • 2019-08-11
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      相关资源
      最近更新 更多