如何使用 MySQL 查询创建和插入 JSON 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40930896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create and insert a JSON object using MySQL queries?
提问by rj_23495
I'm trying to create a JSON object and then read the values from it into MySQL table. But I'm facing errors and I'm new to both JSON and MySQL.
我正在尝试创建一个 JSON 对象,然后将其中的值读取到 MySQL 表中。但是我遇到了错误,而且我对 JSON 和 MySQL 都不熟悉。
SET @j = '{"key1": "value1", "key2": "value2"}';
CREATE TABLE Person (name int,id int);
INSERT INTO Person (name,id) SELECT * FROM OPENJSON(@j) WITH (name int,id int);
回答by saravanabawa
On creating table set your field as JSONdatatype.
在创建表时,将您的字段设置为JSON数据类型。
CREATE TABLE `person` (
`name` json DEFAULT NULL
);
And Insert JSON data into it,
并将 JSON 数据插入其中,
INSERT INTO `person` (`name`)
VALUES ('["name1", "name2", "name3"]');
Or Insert JSON data by Key:Value
或按Key:Value插入 JSON 数据
INSERT INTO person VALUES ('{"pid": 101, "name": "name1"}');
INSERT INTO person VALUES ('{"pid": 102, "name": "name2"}');
Select JSON data,
选择 JSON 数据,
SELECT * FROM `person` WHERE JSON_CONTAINS(name, '["name1"]');
Note: MySQL 5.7 InnoDB or higher version only supports.
注意:仅MySQL 5.7 InnoDB 或更高版本支持。