gpt4 book ai didi

mysql - 如何更新 MySQL 5.7.10 中的 JSON 数据类型列?

转载 作者:IT老高 更新时间:2023-10-28 12:49:04 27 4
gpt4 key购买 nike

我最近开始使用 MySQL 5.7.10,我非常喜欢原生 JSON 数据类型。

但是在更新 JSON 类型值时我遇到了问题。

问题:

下面是表格格式,这里我想在 t1 表格的 JSON data 列中再添加 1 个键。现在我必须获取值修改它并更新表。所以它涉及一个额外的 SELECT 语句。

我可以这样插入

INSERT INTO t1 values ('{"key2":"value2"}', 1);

mysql> select * from t1;
+--------------------+------+
| data | id |
+--------------------+------+
| {"key1": "value1"} | 1 |
| {"key2": "value2"} | 2 |
| {"key2": "value2"} | 1 |
+--------------------+------+
3 rows in set (0.00 sec)

mysql>Show create table t1;


+-------+-------------------------------------------------------------

-------------------------------------------------------+
| Table | Create Table |
+-------+--------------------------------------------------------------------------------------------------------------------+
| t1 | CREATE TABLE `t1` (
`data` json DEFAULT NULL,
`id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------+--------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

有解决办法吗?

最佳答案

感谢@wchiquito 为我指明了正确的方向。我解决了这个问题。这是我的做法。

mysql> select * from t1;
+----------------------------------------+------+
| data | id |
+----------------------------------------+------+
| {"key1": "value1", "key2": "VALUE2"} | 1 |
| {"key2": "VALUE2"} | 2 |
| {"key2": "VALUE2"} | 1 |
| {"a": "x", "b": "y", "key2": "VALUE2"} | 1 |
+----------------------------------------+------+
4 rows in set (0.00 sec)

mysql> update t1 set data = JSON_SET(data, "$.key2", "I am ID2") where id = 2;
Query OK, 1 row affected (0.04 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from t1;
+----------------------------------------+------+
| data | id |
+----------------------------------------+------+
| {"key1": "value1", "key2": "VALUE2"} | 1 |
| {"key2": "I am ID2"} | 2 |
| {"key2": "VALUE2"} | 1 |
| {"a": "x", "b": "y", "key2": "VALUE2"} | 1 |
+----------------------------------------+------+
4 rows in set (0.00 sec)

mysql> update t1 set data = JSON_SET(data, "$.key3", "I am ID3") where id = 2;
Query OK, 1 row affected (0.07 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from t1;
+------------------------------------------+------+
| data | id |
+------------------------------------------+------+
| {"key1": "value1", "key2": "VALUE2"} | 1 |
| {"key2": "I am ID2", "key3": "I am ID3"} | 2 |
| {"key2": "VALUE2"} | 1 |
| {"a": "x", "b": "y", "key2": "VALUE2"} | 1 |
+------------------------------------------+------+
4 rows in set (0.00 sec)

编辑:如果要添加数组,请使用 JSON_ARRAY

update t1 set data = JSON_SET(data, "$.key4", JSON_ARRAY('Hello','World!')) where id = 2;

enter image description here

关于mysql - 如何更新 MySQL 5.7.10 中的 JSON 数据类型列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34986223/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com