首页 > 解决方案 > 具有布尔值的 MySQL JSON_SEARCH 不起作用

问题描述

我遇到了 MySQL JSON_SEARCH 函数的问题,它不支持布尔值搜索。

请参考此 SQL: https ://rextester.com/DYLPJG17389

这是数据库架构:

create table if not exists superheroes (
    name varchar(32),
    attributes JSON
    );

insert into superheroes 
values ('Batman', '{"dead": "false", "orphan": true, "billionaire": "true", "goodboy" : "true"}');

SELECT JSON_SEARCH(attributes, 'all', 'true')
FROM superheroes
WHERE name = 'Batman';

drop table superheroes;

现在结果有: ["$.goodboy", "$.billionaire"]

我需要我的结果应该"$.orphan" 无法替换true"true"因为 JSON 数据来自外部源。

先感谢您。

标签: mysqljson

解决方案


JSON_SEARCH正如文档所说,仅适用于字符串

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

返回 JSON 文档中给定字符串的路径

JSON值也应该用双引号括起来,以表示字符串

JSON 值可以是双引号中的字符串,也可以是数字,也可以是 true 或 false 或 null,也可以是对象或数组

因此,在您的情况下,一种可能的解决方案可能是将 Boolean 转换true为 String "true"。如果无法手动替换,可以使用JSON_REPLACE更改true"true"。由于您已经知道key必须更改值的原因,请使用以下查询来获得所需的结果。

SELECT JSON_SEARCH((JSON_REPLACE(attributes,'$.orphan',"true")), 'all', 'true') 
FROM superheroes
WHERE name = 'Batman';

在此处查看您的演示

输出:

["$.orphan", "$.goodboy", "$.billionaire"]

更新

如果您的密钥orphan同时包含trueand ,您可以使用andfalse仅替换真实值,如下所示。caseJSON_CONTAINS

SELECT JSON_SEARCH(( CASE 
                       WHEN JSON_CONTAINS(attributes, "true", '$.orphan') = 1 
                     THEN 
                       JSON_REPLACE(attributes, '$.orphan', "true") 
                       ELSE attributes 
                     END ), 'all', 'true') 
FROM   superheroes 
WHERE  NAME = 'Batman'; 

演示


推荐阅读