简体   繁体   English

如何以准备好的语句更新mysql 5.7中json列中的键的动态数目

[英]How to update dynamic number of keys in json column in mysql 5.7 as prepared statement

I have created a table in MySQL 5.7 like below. 我已经在MySQL 5.7中创建了一个如下表。

id   :int
data :json

Now data has multiple keys as json. 现在,数据具有多个键作为json。

data = {"a":"b","c":"d"};

Now I have a requirement to update existing data with new data for an update multiple(dynamic) keys in it. 现在,我需要用新数据更新现有数据,以更新其中的多个(动态)键。

How to achieve this. 如何实现这一目标。

You may simply run an UPDATE query by setting the updated object in stringfied form. 您可以通过以字符串形式设置更新的对象来简单地运行UPDATE查询。

For example: Considering you are building a JS application. 例如:考虑您正在构建JS应用程序。

updatedData = JSON.Stringify(updatedData)

query> update t set data = updatedData;

Here's a demo. 这是一个演示。 First I create a table like yours with JSON data. 首先,我使用JSON数据创建一个像您一样的表。

mysql [localhost] {msandbox} (test) > create table t (id int primary key, data json);
Query OK, 0 rows affected (0.02 sec)

mysql [localhost] {msandbox} (test) > insert into t values (1, json_object('a', 'b', 'c', 'd'));
Query OK, 1 row affected (0.01 sec)

mysql [localhost] {msandbox} (test) > select * from t;
+----+----------------------+
| id | data                 |
+----+----------------------+
|  1 | {"a": "b", "c": "d"} |
+----+----------------------+
1 row in set (0.00 sec)

Now I update the JSON data with new values. 现在,我使用新值更新JSON数据。

mysql [localhost] {msandbox} (test) > update t set data = json_merge_patch(data, json_object('a', 123, 'c', 'foo'));
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql [localhost] {msandbox} (test) > select * from t;
+----+------------------------+
| id | data                   |
+----+------------------------+
|  1 | {"a": 123, "c": "foo"} |
+----+------------------------+

For a prepared statement, you should use parameter placeholders as you create the JSON object that will update the data. 对于准备好的语句,在创建将更新数据的JSON对象时,应使用参数占位符。

update t set data = json_merge_patch(data, json_object(?, ?, ?, ?));

I'm not sure what you mean by dynamic keys. 我不确定动态键的含义。 You will have to use parameter placeholders in pairs (1 key, 1 value), and the number of parameters needs to be fixed at the time you prepare the query. 您将必须成对使用参数占位符(1个键,1个值),并且在准备查询时需要固定参数数量。 It's up to you to write application code to build the query with as many parameter placeholders as you need. 由您决定编写应用程序代码以使用所需数量的参数占位符来构建查询。

You should read about JSON functions like JSON_MERGE_PATCH() here: https://dev.mysql.com/doc/refman/5.7/en/json-modification-functions.html 您应该在这里阅读有关JSON_JSON_MERGE_PATCH()之类的JSON函数的信息: https ://dev.mysql.com/doc/refman/5.7/en/json-modification-functions.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM