mysql - 如何在 MySQL 中有条件地更新 JSON 中的字段?

标签 mysql sql json

我们有 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/

相关文章:

php - 锁定 PHP 以实现关键部分 - MySQL 的意外结果

php - 更新选中的复选框数据并删除未选中的数据

jquery - 当 content-type 设置为 application/json 时,JSON.parse() 不起作用

java - 使用 JSON 的 Volley REST 客户端

php - MySQL PHP 图表

python - 使用 Python 将漂亮的汤抓取到 MySQL。卡在 if string contains do else 做其他事情

sql - 当PRIMARY KEY值不连续时,如何获取下一个SQL行?

PHP和SQL上传错误

具有多个where条件的MySQL连接查询

java - 让 GsonConverterFactory 解析某些字段?