[英]mysql JSON_SET can't insert into column with NULL value(5.7+)
I am exploring the JSON funcions of newer mysql server.我正在探索较新的 mysql 服务器的 JSON 功能。 But run into a very rudimentary issue.但是遇到了一个非常初级的问题。
How do I insert {"key":"value"} into a JSON column when I don't know if the current value is NULL or not?当我不知道当前值是否为 NULL 时,如何将 {"key":"value"} 插入 JSON 列?
The table is for illustration only:该表仅供说明:
CREATE TABLE `testjson` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`extra` JSON NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
Test data with NULL and valid json value.使用 NULL 和有效的 json 值测试数据。
| id | extra |
| -: | - |
| 1 | (NULL) |
| 2 | {"name": "james"} |
Desired outcome:期望的结果:
| id | extra |
| -: | - |
| 1 | {"age": 87} |
| 2 | {"age": 87, "name": "james"} |
Now, I try to add {"age":87} into all rows:现在,我尝试将 {"age":87} 添加到所有行中:
UPDATE testjson
SET extra = JSON_SET(extra,'$.age', 87)
;
UPDATE testjson
SET extra = JSON_MERGE(extra,JSON_OBJECT('age', 87)),
;
None of above updates the NULL field.以上都不会更新 NULL 字段。 Tried to set the column default to {}
, but it is not allowed.试图将列默认设置为{}
,但这是不允许的。
Because NULL is not valid JSON data, none of the mysql JSON funcion works: https://dev.mysql.com/doc/refman/5.7/en/json-function-reference.html因为 NULL 不是有效的 JSON 数据,所以 mysql JSON 函数都不起作用: https : //dev.mysql.com/doc/refman/5.7/en/json-function-reference.html
My current work around is to set NULL to {}
before insert, but it is stupid.我目前的解决方法是在插入之前将 NULL 设置为{}
,但这很愚蠢。 An simple update should not use two queries.一个简单的更新不应使用两个查询。
How do you guys handle this?你们是怎么处理这件事的?
使用合并:
UPDATE testjson SET extra = JSON_SET(COALESCE(extra, '{}'), '$.age', 87);
SET extra = JSON_SET(IFNULL(extra, "{}"), "$.age", 87)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.