如何在mysql中搜索json数据?

时间:2018-04-08 06:28:26

标签: mysql sql json

我有描述字段。该字段是json

描述字段的包含如下:

{
    "address": 
    {
        "street": "street 123", 
        "information": 
        {
            "province": "province 123",
            "regency": "regency 123", 
            "district": "district 123"
        }
    }, 
    "mobileNumber": "123"
}

我想在json数据中搜索省

我试着这样:

SELECT * FROM orders WHERE LOWER(JSON_EXTRACT(description, "$.address.information.province")) LIKE "%prov%"

结果为空

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

问题是您的JSON无效。

之后不应该有逗号
"district": "district 123", 

"mobileNumber": "123",

如果您尝试使用有效的JSON,您将获得预期的结果:

select json_extract('{ "address": { "street": "street 123",         "information": { "province": "province 123",  "regency": "regency 123",             "district": "district 123" } }, "mobileNumber": "123"}', '$.address.information.province')

"province 123"

我创建了一个db-fiddle,它似乎可以正常处理您的数据:

create table x (id int, description json);
insert into x values(1, '{    "address":     {        "street": "street 123",         "information":         {            "province": "province 123",            "regency": "regency 123",             "district": "district 123"         }    },     "mobileNumber": "123"}');
select * from x where json_extract(description, '$.address.information.province') like '%prov%'

输出

id  description
1   {"address": {"street": "street 123", "information": {"regency": "regency 123", "district": "district 123", "province": "province 123"}}, "mobileNumber": "123"} 

答案 1 :(得分:-1)

三件事:

1.当使用mysql函数' JSON_EXTRACT'时,请将数据类型设为' json';

2.你的json data.deleted 2逗号有问题。右边的json应该是这样的:

SELECT * FROM orders WHERE JSON_EXTRACT(description, "$.address.information.province") LIKE "%prov%"

3.它区分大小写。试试这个:

makemigrations