【问题标题】:Issue with searching for object property in array for JSON data type在 JSON 数据类型的数组中搜索对象属性的问题
【发布时间】:2016-09-08 00:18:13
【问题描述】:

我有以下架构,value 作为 JSON 类型

mysql> select * from people;
+------+---------------------------------------------------------------------------+
| id   | value                                                                     |
+------+---------------------------------------------------------------------------+
| blah | {"key1": "value1", "key2": "value2"}                                      |
| foo  | {"key1": "value1", "friends": [{"friendId": "123"}, {"friendId": "foo"}]} |
+------+---------------------------------------------------------------------------+

我预计下面的查询会返回行 foo,但它没有。

mysql> select * from people where value->'$.friends[*].friendId' = "123";
Empty set 

条件value->'$.friends[*].friendId' 似乎有效,因为它适用于以下查询:

mysql> select value->'$.friends[*].friendId' from people;
+---------------------------------+
| value->'$.friends[*].friendId' |
+---------------------------------+
| NULL                            |
| ["123", "foo"]                  |
+---------------------------------+

那么为什么查询select * from people where value->'$.friends[*].friendId' = "123"; 没有返回结果呢?

【问题讨论】:

    标签: mysql jsonpath mysql-5.7 mysql-json


    【解决方案1】:

    JSON_CONTAINS 与我感兴趣的 JSON 数组值一起使用:

    select * from people where JSON_CONTAINS (value, {"friends": [{"friendId": "123"}]});
    

    【讨论】:

    • 如果friends 数组中的对象有更多字段,这也有效。所有指定的值必须与要返回的行匹配。所以它就像一个AND 运算符。例如,如果friends 数组中的对象还有一个字段name,那么上述查询仍将返回相同的结果。如果您指定JSON_CONTAINS (value, {"friends": [{"friendId": "123", "name": "Andrew"}]}),则只会返回具有friendId=123name=Andrew 的行。
    猜你喜欢
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多