我正在尝试从mySQL数据库表中检索一些信息,在该表中我将创建json类型的列。在这里,我要输入一个完整的json数组,其中包含各个json。
{"Date": "2019-09-30", "TableName": "es_apn_1", "Count": "3"}, {"Date": "2019-09-30", "TableName": "es_response_1", "Count": "297"}, {"Date": "2019-09-30", "TableName": "es_group_1", "Count": "356"}
所以我正尝试使用json_array()和json_object()获取单个json,然后获取它们各自的值。
我试图像这样简单地输入json:
{"Date": "2019-09-30", "TableName": "es_apn_1", "Count": "3"}, {"Date": "2019-09-30", "TableName": "es_response_1", "Count": "297"}, {"Date": "2019-09-30", "TableName": "es_group_1", "Count": "356"}
或类似如下的数组形式:
[{"Date": "2019-09-30", "TableName": "es_apn_1", "Count": "3"}, {"Date": "2019-09-30", "TableName": "es_response_1", "Count": "297"}, {"Date": "2019-09-30", "TableName": "es_group_1", "Count": "356"}]
或在json中
{{"Date": "2019-09-30", "TableName": "es_apn_1", "Count": "3"}, {"Date": "2019-09-30", "TableName": "es_response_1", "Count": "297"}, {"Date": "2019-09-30", "TableName": "es_group_1", "Count": "356"}}
我用来获取结果的查询是:
select json_object(js,'Date'), json_object(js,'TableName'), json_object(js,'Count') from (select json_array(jsondata) as js);
其中jsondata是上述条目所在的列的名称。
但是我得到这种格式的结果eveytime。
{"[\"{\\\"Date\\\": \\\"2019-09-30\\\", \\\"TableName\\\": \\\"es_apn_1\\\", \\\"Count\\\": \\\"3\\\"}, {\\\"Date\\\": \\\"2019-09-30\\\", \\\"TableName\\\": \\\"es_response_1\\\", \\\"Count\\\": \\\"297\\\"}, {\\\"Date\\\": \\\"2019-09-30\\\", \\\"TableName\\\": \\\"es_group_1\\\", \\\"Count\\\": \\\"356\\\"}\"]": "Date"} | {"[\"{\\\"Date\\\": \\\"2019-09-30\\\", \\\"TableName\\\": \\\"es_apn_1\\\", \\\"Count\\\": \\\"3\\\"}, {\\\"Date\\\": \\\"2019-09-30\\\", \\\"TableName\\\": \\\"es_response_1\\\", \\\"Count\\\": \\\"297\\\"}, {\\\"Date\\\": \\\"2019-09-30\\\", \\\"TableName\\\": \\\"es_group_1\\\", \\\"Count\\\": \\\"356\\\"}\"]": "TableName"} | {"[\"{\\\"Date\\\": \\\"2019-09-30\\\", \\\"TableName\\\": \\\"es_apn_1\\\", \\\"Count\\\": \\\"3\\\"}, {\\\"Date\\\": \\\"2019-09-30\\\", \\\"TableName\\\": \\\"es_response_1\\\", \\\"Count\\\": \\\"297\\\"}, {\\\"Date\\\": \\\"2019-09-30\\\", \\\"TableName\\\": \\\"es_group_1\\\", \\\"Count\\\": \\\"356\\\"}\"]": "Count"}
您能为我提供查询或输入内容的格式吗?
答案 0 :(得分:0)
您可以使用以下命令进行操作:
CREATE TABLE tbl (id int auto_increment primary key, jdat json);
INSERT INTO tbl (jdat)
VALUES ('[{"Date": "2019-09-30", "TableName": "es_apn_1", "Count": "3"},
{"Date": "2019-09-30", "TableName": "es_response_1", "Count": "297"},
{"Date": "2019-09-30", "TableName": "es_group_1", "Count": "356"}]');
select JSON_EXTRACT(jdat,'$[0].Date') from tbl
在此处查看我的小演示:https://rextester.com/DPQ80237
@Raymond Nijland的评论非常正确,建议将此类信息存储在适当的表中,如此处所示:
create table tbl2 (id int auto_increment primary key, refid int, tdate date, tname nvarchar(32), tcount int);
INSERT INTO tbl2 (refid, tdate, tname, tcount)
VALUES (1,'2019-09-30','es_apn_1',3),
(1,'2019-09-30','es_response_1',297),
(1,'2019-09-30','es_group_1',356);
采用这种设计,所包含的数据更容易用于搜索或与其他表一起访问JOIN
……