【问题标题】:MySQL json_search on numeric valuesMySQL json_search 上的数值
【发布时间】:2017-12-03 06:02:15
【问题描述】:

我有一个这样的对象的 json 列表

[{
    "something": "bla",
    "id": 2
}, {
    "something": "yes",
    "id": 1
}]

我的id 字段始终是一个数值。但是当我尝试查找id = 2 时,MySQL 返回NULL

select
    json_search(
        json_extract(
            '[{"something": "bla" ,"id": 2}, {"something": "yes","id": 1}]',
            "$[*].id"
        ),
        'one',
        2
    ) as json_search;

json_search |
------------|
            |

当我在我的 json id 对象中使用字符串作为值而不是数值时,我得到了索引为 0 的结果。

select
    json_search(
        json_extract(
            '[{"something": "bla" ,"id": "2"}, {"something": "yes","id": 1}]',
            "$[*].id"
        ),
        'one',
        "2"
    ) as json_search;

json_search |
------------|
"$[0]"      |

我使用的是 MySQL 5.7.17

@@version  |
-----------|
5.7.17-log |

MySQL 中没有提供 json 数组中的数字搜索吗?

【问题讨论】:

    标签: mysql sql json


    【解决方案1】:

    您可以尝试一些复杂、不直观且可能存在性能问题的东西,但这是一种选择:

    mysql> SELECT JSON_SEARCH(
        ->   REPLACE(
        ->     REPLACE(
        ->       REPLACE(
        ->         JSON_EXTRACT('[
        '>                         {"something": "bla" ,"id": 2},
        '>                         {"something": "yes","id": 1}
        '>                       ]', "$[*].id"),
        ->       ', ', '","'),
        ->     '[', '["'),
        ->   ']', '"]'),
        -> 'one', '2') `json_search`;
    +-------------+
    | json_search |
    +-------------+
    | "$[0]"      |
    +-------------+
    1 row in set (0.00 sec)
    

    【讨论】:

    • 好的,这行得通。但实际上,它看起来并不直观,我担心真实数据会很慢。
    【解决方案2】:

    虽然JSON_EXTRACT 函数返回[2, 1] 并且它是一个有效的JSON,但如果您搜索documentation JSON_SEARCH 函数是:

    JSON_SEARCH(json_doc, one_or_all, search_str[, escape_char[, path] ...])

    因此,据我了解,您只能使用 STRING 值,而不能使用数值。但是解决您的问题的一种方法可能是使用 JSON_CONTAINS 函数,因为无论数值是否存在,它都会返回 1 或 0。

    select
        json_contains(
            json_extract(
                '[{"something": "bla" ,"id": 2}, {"something": "yes","id": 1}]',
                "$[*].id"
            ),
            "2"
        ) as json_contains;
    

    唯一的问题是您无法获取 JSON 文档中给定值的路径。希望对您有所帮助。

    【讨论】:

    • 但是我必须使用字符串值作为搜索值......也不是很令人满意
    猜你喜欢
    • 2019-02-23
    • 2017-03-14
    • 2021-05-02
    • 2021-10-23
    • 2021-07-11
    • 2017-12-07
    • 2020-07-30
    • 2019-09-23
    • 2016-10-17
    相关资源
    最近更新 更多