我们有 Student 表,它在“jsonData”列(longtext)中包含 JSON。 我们需要更改 json 中“isHandicapped”字段的值。
结构:
{
"data": {
"schoolData": {
"studentListe": [
{
"student": {
"studentId": 111749,
"isHandicapped": false
}
}
],
},
}
}
旧数据:“isHandicapped”:false
新值:“isHandicapped”:“NO”
这应该是条件更新,因为我们需要将值更改为 true
旧数据:“isHandicapped”:true
新值:“isHandicapped”:“Ja”
表的主要字段是 ID。
我得到了相同的 SQL 查询,但无法理解如何添加条件更新,如果值为真,则将 Ja 否则为 NO:
update Student
set data = JSON_SET(data, "'$."data"."schoolData"."studentListe"[*]."isHandicapped", "?")
where id = 2;
最佳答案
以下是提取该字段的方法:
select json_extract(data, '$.data.schoolData.studentListe[*].student.isHandicapped') from Student;
+-------------------------------------------------------------------------------+
| json_extract(data, '$.data.schoolData.studentListe[*].student.isHandicapped') |
+-------------------------------------------------------------------------------+
| [false] |
+-------------------------------------------------------------------------------+
您可以使用 JSON_SET() 为特定数组成员 0 设置一个值:
update student set data = json_set(data, '$.data.schoolData.studentListe[0].student.isHandicapped', 'NO');
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
select json_extract(data, '$.data.schoolData.studentListe[*].student.isHandicapped') from Student;
+-------------------------------------------------------------------------------+
| json_extract(data, '$.data.schoolData.studentListe[*].student.isHandicapped') |
+-------------------------------------------------------------------------------+
| ["NO"] |
+-------------------------------------------------------------------------------+
但是你不能使用*
通配符来更新所有的数组成员:
update student set data = json_set(data, '$.data.schoolData.studentListe[*].student.isHandicapped', '"NO"');
ERROR 3149 (42000): In this situation, path expressions may not contain the * and ** tokens or an array range.
这几天在 Stack Overflow 上看到很多关于在 MySQL 中选择或修改 JSON 数据的问题。通常答案是:
如果您需要选择或更新 JSON 文档中的字段,则不应以 JSON 格式存储数据。
如果您将数据存储在普通的表和列中,这种类型的任务很容易解决:
UPDATE StudentListe
SET isHandicapped = 'NO'
WHERE studentId = 2;
关于mysql - 如何在 MySQL 中有条件地更新 JSON 中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42264346/