How to create and insert a JSON object using MySQL queries?

心已入冬 提交于 2020-11-30 06:46:49

问题


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.

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);

回答1:


On creating table set your field as JSON datatype.

CREATE TABLE `person` (
  `name` json DEFAULT NULL
);

And Insert JSON data into it,

INSERT INTO `person` (`name`)
VALUES ('["name1", "name2", "name3"]');

Or Insert JSON data by Key:Value

INSERT INTO person VALUES ('{"pid": 101, "name": "name1"}');
INSERT INTO person VALUES ('{"pid": 102, "name": "name2"}');

Select JSON data,

SELECT * FROM `person` WHERE JSON_CONTAINS(name, '["name1"]');

Note: MySQL 5.7 InnoDB or higher version only supports.



来源:https://stackoverflow.com/questions/40930896/how-to-create-and-insert-a-json-object-using-mysql-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!