【问题标题】:use JSON_EXTRACT, JSON_SET, JSON_REPLACE, JSON_INSERT in json array在 json 数组中使用 JSON_EXTRACT、JSON_SET、JSON_REPLACE、JSON_INSERT
【发布时间】:2018-08-17 09:08:37
【问题描述】:

我在mysql 中有一个名为names 的json 类型列,它是一个简单的json 数组(不是键/值)。我找不到任何使用JSON_EXTRACTJSON_SETJSON_REPLACEJSON_INSERT 用于简单 json 数组字段的示例。

我知道还有其他方法可以操作json字段类型的json数组,但是可以将这些函数用于json数组吗?

例如,name 字段包含["A","B","C"],如何使用这些函数对这个 json 进行更新、插入和删除?

更新

查询必须从 php 脚本执行

【问题讨论】:

    标签: mysql json


    【解决方案1】:

    您引用的所有函数都完全按照manual 中描述的预期工作;也就是说JSON_SET 将在值已存在时插入或替换,JSON_INSERT 将在值不存在时插入,JSON_REPLACE 将替换预先存在的值。您可以使用 JSON_ARRAY_INSERTJSON_ARRAY_APPEND 更轻松地向 JSON 数组添加值。

    -- extract second element
    select json_extract('["A", "B", "C"]', '$[1]')
    -- "B"
    
    -- replace second element
    select json_set('["A", "B", "C"]', '$[1]', 'D')
    -- ["A", "D", "C"]
    
    -- insert fourth element
    select json_set('["A", "B", "C"]', '$[3]', 'E')
    -- ["A", "B", "C", "E"]
    
    -- attempt to insert second element fails as it already exists
    select json_insert('["A", "B", "C"]', '$[1]', 'F')
    -- ["A", "B", "C"]
    
    -- use json_array_insert to insert a new second element and move the other elements right
    select json_array_insert('["A", "B", "C"]', '$[1]', 'F')
    -- ["A", "F", "B", "C"]
    
    -- insert fourth element
    select json_insert('["A", "B", "C"]', '$[3]', 'F')
    -- ["A", "B", "C", "F"]
    
    -- or use json_array_append to add an element at the end
    select json_array_append('["A", "B", "C"]', '$', 'F')
    -- ["A", "B", "C", "F"]
    
    -- replace second element
    select json_replace('["A", "B", "C"]', '$[1]', 'G')
    -- ["A", "G", "C"]
    
    -- attempt to replace non-existing element fails
    select json_replace('["A", "B", "C"]', '$[3]', 'G')
    -- ["A", "B", "C"]
    

    Demo on dbfiddle

    要在表中的列上使用这些函数,只需将上述调用中的["A", "B", "C"] 替换为列名,例如:

    create table test (j json);
    insert into test values ('["A", "B", "C"]');
    select json_array_insert(j, '$[1]', 'F') 
    from test
    -- ["A", "F", "B", "C"]
    

    Demo on dbfiddle

    【讨论】:

    • 感谢您的回答,我只是更新了问题,我不是从控制台运行查询,而是从 php 脚本运行查询。我需要提供表名和字段名。你能举例查询能够通过脚本执行吗? $[1]$[3] 是什么?
    • 如果你想运行一个 php 脚本,你可以使用 fetch javascript 命令来完成。查询插入到 php 脚本中。
    • json_array_insert 可用于在数组中间插入新元素,如下所示:json_array_insert('["A","B","C"]', '$[1]', 'D');
    • @Guss 你是对的,我没有谈论json_array_insertjson_array_append,因为OP 正在谈论一组特定的功能。但是为了完整起见,它们应该在答案中,所以我添加了它们。感谢您的反馈
    【解决方案2】:

    我认为找到了解决方案

    对于json数组,不能通过数组值使用JSON_EXTRACTJSON_SETJSON_REPLACEJSON_INSERT,而且你必须知道每个值在json数组中的位置(我认为这是一个弱点)。

    例如要选择第二个值,您可以使用$[1], 但是对于插入值,您可以使用 JSON_ARRAY_APPENDJSON_ARRAY_INSERT

    【讨论】:

      猜你喜欢
      • 2018-04-13
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 2022-12-22
      • 2021-10-30
      • 1970-01-01
      相关资源
      最近更新 更多