JSON_SET,使用另一个json更新

时间:2019-09-26 07:10:34

标签: mysql

我在person_data列中具有以下json结构:

{"name":"john","surname":"smith"}

现在,我想用他的爱好的json更新:

$hobbies = {"c1":"cycling","c2":"swimming"};

Mysql:

UPDATE people 
SET person_data = JSON_SET(person_data, '$.hobbies', $hobbies) 
WHERE id='1';

但是问题是,它是作为字符串插入$.hobbies

下的

我也尝试过:

JSON_SET(person_data, 
         '$.hobbies','',
         '$.hobbies.c1','cycling',
         '$.hobbies.c2','swimming');

但是我得到的只是"hobbies":""

我想要的是:

"hobbies": {"c1":"cycling","c2":"swimming"}

1 个答案:

答案 0 :(得分:2)

这是两种可能的方式。

使用JSON_OBJECT()从属性及其值创建JSON对象:

JSON_SET(
  person_data, 
  '$.hobbies',
  JSON_OBJECT('c1', 'cycling', 'c2', 'swimming')
)

Cast JSON字符串为JSON类型:

JSON_SET(
  person_data,
  '$.hobbies',
  CAST('{"c1":"cycling","c2":"swimming"}' as JSON)
)

两者都会创建一个这样的JSON对象:

{"name": "john", "hobbies": {"c1": "cycling", "c2": "swimming"}, "surname": "smith"}

db-fiddle上观看演示