我在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"}
答案 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上观看演示