我在mysql中有一个名为names的json类型列,它是一个简单的json数组(不是key/value)。对于简单的json数组字段,我找不到使用JSON_EXTRACT、JSON_SET、JSON_REPLACE、JSON_INSERT的任何示例。
我知道在json字段类型中还有其他方法来操作json数组,但是是否可以将这些函数用于json数组呢?
例如,name字段包含["A","B","C"],如何使用这些函数对此json执行更新、插入和删除?
更新
查询必须从php脚本执行。
发布于 2018-08-17 09:27:10
您所引用的所有函数的工作方式与手册中所期望的和描述的完全相同;也就是说,如果某个值已经存在,JSON_SET将插入或替换;如果某个值不存在,JSON_INSERT将插入或替换;而JSON_REPLACE将替换先前存在的值。您可以使用JSON_ARRAY_INSERT和JSON_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"]要在表中的列上使用这些函数,只需将上述调用中的["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"]发布于 2018-08-17 17:51:26
我想找到了解决办法
对于json数组,不可能按数组值使用JSON_EXTRACT、JSON_SET、JSON_REPLACE、JSON_INSERT,而且您必须知道每个值在json数组中的位置(我认为这是一个弱点)。
例如,要选择第二个值,可以使用$[1],但对于插入值,可以使用JSON_ARRAY_APPEND和JSON_ARRAY_INSERT。
https://stackoverflow.com/questions/51891984
复制相似问题