繁体   English   中英

MariaDB / MySQL-如何根据嵌套对象的键查询JSON

[英]MariaDB/MySQL - How to query JSON based on key of nested object

给定存储在MariaDB / MySQL中的以下JSON对象:

SET @j = '{
    "thing": {
        "sub_things": [
            {
                "attribute": [
                    { "1": 40 },
                    { "5": 25 },
                    { "13": 35 }
                ]
            },
            {
                "attribute": [
                    { "2": 50 },
                    { "7": 50 }
                ]
            }
        ]
    }
}'

我将如何查询它以返回sub_things ,其中attribute数组中的一个对象具有特定键,例如,如果键为13,则应返回第一个sub_thing

谢谢!

我不确定在单个查询中是否可以实现所需的功能。

以下存储过程也许可以给您一些想法(该存储过程适用于MariaDB和MySQL):

> DROP PROCEDURE IF EXISTS `JSON_query_based_on_key`;
Query OK, 0 rows affected (0.01 sec)

> DELIMITER //

> CREATE PROCEDURE `JSON_query_based_on_key`(
->   `json` TEXT,
->   `key` VARCHAR(5)
-> )
-> BEGIN
->   DECLARE `sub_things_current` INT
->      DEFAULT JSON_LENGTH(`json`, '$.thing.sub_things') - 1;
-> 
->   WHILE (`sub_things_current` > -1) DO
->     IF NOT JSON_CONTAINS_PATH(
->       `json`, 
->       'one', 
->       CONCAT('$.thing.sub_things[', `sub_things_current`, '].attribute[*]."', `key`, '"')
->     ) THEN
->       SET `json` := JSON_REMOVE(
->         `json`,
->         CONCAT('$.thing.sub_things[', `sub_things_current`, ']'));
->     END IF;
->     SET `sub_things_current` := `sub_things_current` - 1;
->   END WHILE;
-> 
->   SELECT JSON_EXTRACT(`json`, '$.thing');
-> END//
Query OK, 0 rows affected (0.00 sec)

> DELIMITER ;

> CALL `JSON_query_based_on_key`('{
'>   "thing": {
'>     "sub_things": [
'>       {
'>         "attribute": [
'>           { "1": 40 },
'>           { "5": 25 },
'>           { "13": 35 }
'>         ]
'>       },
'>       {
'>         "attribute": [
'>           { "2": 50 },
'>           { "7": 50 }
'>         ]
'>       }
'>     ]
'>   }
'> }', '13');
+---------------------------------------------------------------------+
| JSON_EXTRACT(`json`, '$.thing')                                     |
+---------------------------------------------------------------------+
| {"sub_things": [{"attribute": [{"1": 40}, {"5": 25}, {"13": 35}]}]} |
+---------------------------------------------------------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

根据需要修改代码。

有关MariaDB(10.2.6)的信息,请参见db <> fiddle ;有关MySQL(5.7.17)的信息,请参见db -fiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM