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

时间:2017-07-17 11:50:47

标签: mysql sql json mariadb

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

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

如何查询此内容以返回sub_things attribute数组中的某个对象具有特定键的sub_thing,例如如果键为13,则应返回第一个window.Highcharts = require('highcharts'); require('highcharts-exporting')(Highcharts); require('highcharts-more')(Highcharts);

谢谢!

1 个答案:

答案 0 :(得分:4)

我不确定在一个查询中,您是否可以实现所需。

以下存储过程可能会给你一些想法(存储过程适用于MariaDB和MySQL):

arr = [ {a: "1", b: "1", c: "ham"}, {a: "2", b: "1", c: "Thór"}, {a: "3", b: "1", c: "Soçao"}]

var results = function(word) {
    var limit = LIMIT_RESULTS + 1;
    var out = [];
    var partialLimit = 0;
    var outaux = [];    



    // search by c:

    outaux = alasql('SELECT a, b, c + "''" as n\
                        FROM ? WHERE c LIKE "%'+word+'%" ORDER BY c LIMIT ' + partialLimit, [arr]);
    out.push.apply(out, outaux);

根据需要修改代码。

请参阅db<>fiddle了解MariaDB(10.2.6)和db-fiddle了解MySQL(5.7.17)。