跳到主要内容
翻译页面

本页面由 AI 辅助从英文翻译而来。如两者存在差异,以英文版本为准。

JSON_SET

在 JSON 文档的指定路径处更新现有值或插入新值。

另请参阅:
[SELECT] [JSON_EXTRACT] [JSON_SET] [JSON_REPLACE]


语法​

SELECT JSON_SET(json_column, path, value_to_set) FROM <multipartIdentifier>;

参数​

json_column
要修改的 JSON 列或表达式。

path
指明在何处设置值的 JSON 路径表达式。如果路径存在,则更新该值;如果路径不存在,则添加新的键值对。

value_to_set
要在 JSON 文档的指定路径处设置的值。

返回值​

返回在指定路径处设置了值的 JSON 文档。如果路径存在,则更新现有值;否则添加新的键值对。

键已存在时的行为
函数已存在时是否覆盖?不存在时是否创建?
json_insert()否是
json_replace()是否
json_set()是是

示例​

更新 JSON 对象中的现有值​

-- Example: Update the 'status' key's value to 'active' in a JSON object
SELECT JSON_SET(json_data, '$.status', 'active') as updated_json
FROM cloud_services
WHERE service_id = 'service123';

-- Expected output:
-- |---------------------------------------------------------|
-- | updated_json |
-- |---------------------------------------------------------|
-- | {"name":"ServiceOne", "status":"active", "region":"US"} |
-- |---------------------------------------------------------|

如果 'status' 键存在,此查询会将 JSON 文档中的 'status' 键更新为 'active'。如果文档中不存在 'status',则以值 'active' 添加该键。

向 JSON 对象添加新的键值对​

-- Example: Add a new key 'lastChecked' with the current date to a JSON object
SELECT JSON_SET(json_data, '$.lastChecked', '2024-04-29') as updated_json
FROM cloud_services
WHERE service_id = 'service123';

/* expected output...
|-----------------------------------------------------------------------|
| updated_json |
|-----------------------------------------------------------------------|
| {"name":"ServiceOne", "status":"pending", "lastChecked":"2024-04-29"} |
|-----------------------------------------------------------------------|
*/

如果 'lastChecked' 尚不存在,此查询会向 JSON 文档添加一个值为 '2024-04-29' 的新键 'lastChecked'。如果已存在,则将现有值更新为 '2024-04-29'。