------------------------ 数组 ------------------------
> 数组提取
-- ------------------------------ 提取 JSON_EXTRACT ------------------------------ -- 定义数组 SET @mapJSON = '[{"id":"10000004555096","name":"1.docx","format":"docx","type":0},{"id":"10000004555098","name":"2.doc","format":"doc","type":0},{"id":"10000004555097","name":"3.html","format":"html","type":1}]'; -- 提取数组下标为 0 的元素 SELECT JSON_EXTRACT(@mapJSON, "$[0]") AS result; -- {"id": "10000004555096", "name": "1.docx", "type": 0, "format": "docx"} -- 提取数组每个元素的字段 name SELECT JSON_EXTRACT(@mapJSON, "$[*].name") AS result; -- ["1.docx", "2.doc", "3.html"] -- 提取数组下标为 1 的元素的字段 name SELECT JSON_EXTRACT(@mapJSON, "$[1].name") AS result; -- "2.doc" -- 提取数组下标为 2 的元素的字段 type SELECT JSON_EXTRACT(@mapJSON, "$[2].type") AS result; -- 1
> 数组查找
-- ------------------------------ 查找 JSON_CONTAINS ------------------------------ -- 定义数组 SET @mapJSON = '[{"id":"10000004555096","name":"1.docx","format":"docx","type":0},{"id":"10000004555098","name":"2.doc","format":"doc","type":0},{"id":"10000004555097","name":"3.html","format":"html","type":1}]'; -- 示例1:查找 id 等于 10000004555096 的元素 SELECT JSON_CONTAINS(JSON_EXTRACT(@mapJSON, "$[*]"), JSON_OBJECT('id', '10000004555096')) AS result; -- 1 -- 示例1:查找 name 等于 3.htm1 的元素 SELECT JSON_CONTAINS(JSON_EXTRACT(@mapJSON, "$[*].name"), '"3.html"') AS result; -- 1 SELECT JSON_CONTAINS(JSON_EXTRACT(@mapJSON, "$[*].name"), '"3.HTML"') AS result; -- 0