JSON 可以存储在具有不同数据类型的数据库中。即 JSON、VACRHAR、TEXT...等。对于导出报告或过滤 JSON 元素值,我们应该有不同的解决方案来完成它。
创建一个表以将 JSON 存储在 MySQL 表中。
CREATE TABLE test_Json(id INT, activity_log JSON);
将样本数据插入表中。JSON 字段数据以 JSON 数据类型插入,但也可以是 VARCHAR 或 Text 类型。
INSERT INTO test_Json(id, activity_log)
VALUES(1,
'{
"log": [
{
"datetime": "2017-10-25 07:19:55",
"Activity": "Activity 1"
},
{
"datetime": "2017-10-25 07:20:05",
"Activity": "Activity 2"
},
{
"datetime": "2017-10-25 07:20:31",
"Activity": "Activity 3"
},
{
"datetime": "2017-10-25 07:20:31",
"Activity": "Activity 4"
},
{
"datetime": "2017-10-25 07:21:03",
"Activity": "Activity 5"
},
{
"datetime": "2017-10-25 13:56:42",
"Activity": "Activity 6"
},
{
"datetime": "2017-10-25 13:56:53",
"Activity": "Activity 7"
},
{
"datetime": "2017-10-25 13:57:03",
"Activity": "Activity 8"
},
{
"datetime": "2017-10-25 13:57:04",
"Activity": "Activity 9"
}, { "datetime": "2017-10-25 13:57:53",
"Activity": "Activity 10"
},
{
"datetime": "2017-10-25 13:57:59",
"Activity": "Activity 11"
},
{
"datetime": "2017-10-25 13:58:01",
"Activity": "Activity 12"
},
{
"datetime": "2017-10-25 13:58:01",
"Activity": "Activity 13"
}
]
} ');
INSERT INTO test_Json(id, activity_log)
VALUES(2,'
{
"log": [
{ "datetime": "2017-10-29 21:56:27",
"Activity": "Activity-11"
},
{
"datetime": "2017-10-29 21:56:27",
"Activity": "Activity-12"
},
{
"datetime": "2017-10-29 21:56:27",
"Activity": "Activity-13"
},
{
"datetime": "2017-10-29 21:56:27",
"Activity": "Activity-14"
},
{
"datetime": "2017-10-29 21:56:35",
"Activity": "Activity-15"
},
{
"datetime": "2017-10-29 21:56:49",
"Activity": "Activity-16"
},
{
"datetime": "2017-10-29 21:56:49",
"Activity": "Activity-17"
},
{
"datetime": "2017-10-29 21:56:49",
"Activity": "Activity-18"
}
]
}');
查询以将 JSON 导出为具有 JSON 长度值的 JSON 数组
SELECT TJ.id,
JSON_LENGTH(JSON_EXTRACT(TJ.activity_log, '$**.datetime')) as Json_Length,
JSON_EXTRACT(TJ.activity_log, '$**.datetime') as json_array_message,
JSON_EXTRACT(TJ.activity_log, '$**.Activity') as json_array_datetime
FROM test_Json TJ
WHERE JSON_VALID(TJ.activity_log) = 1;
JSON_VALID()
将验证 JSON 列数据,无论 JSON 数据是否正确。如果不是,那么它将从查询中过滤掉。
递归 CTE(公用表表达式)以行格式获取 n 级元素值
WITH RECURSIVE CTE_json (id, array_datetime, array_message,seq) AS
(
SELECT id,
JSON_EXTRACT(JSON_EXTRACT(activity_log, '$**.datetime'), CONCAT('$[', 0, ']')),
JSON_EXTRACT(JSON_EXTRACT(activity_log, '$**.Activity'), CONCAT('$[', 0, ']')),
0 as seq
FROM test_Json
UNION ALL
SELECT TJ.id,
JSON_EXTRACT(JSON_EXTRACT(TJ.activity_log, '$**.datetime'), CONCAT('$[', rc.seq +1, ']')) as array_datetime,
JSON_EXTRACT(JSON_EXTRACT(TJ.activity_log, '$**.Activity'), CONCAT('$[', rc.seq +1, ']')) as array_message,
rc.seq +1 AS seq
FROM CTE_json rc
INNER JOIN test_Json TJ ON rc.id = TJ.id
WHERE rc.seq+1 < JSON_LENGTH(JSON_EXTRACT(TJ.activity_log, '$**.datetime'))
)
SELECT *
FROM CTE_json cj
ORDER BY id, seq;
如果当前 MySQL 版本不支持递归 CTE,那么我们可以使用其他 LOOP 替代方案。