mysql 如何更新JSON值的一部分

2w3kk1z5  于 2023-11-16  发布在  Mysql
关注(0)|答案(2)|浏览(90)

我有以下数据和MySQL表:

CREATE TABLE my_tbl(
  id INT,
  dataset_query longtext
);
INSERT INTO my_tbl(id, dataset_query) VALUES (1, '{"database":1,"native":{"query":"SELECT * FROM view_1.device","template-tags":{}},"type":"native"}');
INSERT INTO my_tbl(id, dataset_query) VALUES (2, '{"database":1,"native":{"query":"SELECT id, name FROM view_1.request","template-tags":{}},"type":"native"}');
INSERT INTO my_tbl(id, dataset_query) VALUES (3, '{"database":3,"native":{"query":"SELECT id, name, age FROM view_3.person","template-tags":{}},"type":"native"}');

字符串
我需要更改dataset_query列中的以下数据:

  • "database":1"database":2
  • view_1替换为view_2

为了更新数据库ID,我使用以下SQL语句:

UPDATE
    my_tbl
SET
    dataset_query = JSON_SET(dataset_query, "$.database", 2) 
WHERE 
    json_extract(dataset_query, '$.database') = 1;


如何更新my_tbl表中的dataset_query列,以将所有出现的view_1替换为view_2
预期结果如下:
| ID|数据集查询|
| --|--|
| 1 |{“database”:2,“native”:{“query”:“SELECT * FROM view_2.device”,“template-tagers”:{}},“type”:“native”:{“query”:“SELECT * FROM view_2.device”,“template-tagers”:{}}|
| 2 |{“database”:2,“native”:{“query”:“SELECT id,name FROM view_2.request”,“template-tagers”:{}},“type”:“native”}|
| 3 |{“database”:3,“native”:{“query”:“SELECT id,name,age FROM view_3.person”,“template-tagers”:{}},“type”:“native”}|
Db fiddle:https://www.db-fiddle.com/f/nw7sEBcF2i8eioWQawqdmD/0

qvsjd97n

qvsjd97n1#

使用REPLACE()函数。使用路径$.native.query获取嵌套对象属性。

UPDATE my_tbl
SET dataset_query = JSON_REPLACE(
        dataset_query, 
        '$.native.query',
        REPLACE(dataset_query->>'$.native.query', 'view_1', 'view_2'))
WHERE dataset_query->>'$.native.query' LIKE '%view_1%';

字符串

ryevplcw

ryevplcw2#

update my_tbl
set dataset_query = JSON_SET(
  dataset_query, '$.native.query',
  REPLACE(
    JSON_UNQUOTE(JSON_EXTRACT(dataset_query, '$.native.query')),
    'view_1', 'view_2'
  )
);

字符串
Db fiddle:https://www.db-fiddle.com/f/t3jyZcYR33X9wHZPQ6sahf/1

相关问题