mysql - 具有布尔值的 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 数据来自外部源。
先感谢您。
解决方案
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
同时包含true
and ,您可以使用andfalse
仅替换真实值,如下所示。case
JSON_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';
推荐阅读
- flutter - Flutter - 如何将“中间光标”添加到 SingleChildScrollView?
- kubernetes-helm - 仅在不存在时安装 helm 子图资源
- visual-studio-code - 如何在vscode中保存整个Webview
- java - 是否可以循环创建spring bean?
- npm - 如何将以前全局安装的 npm 包安装到我的 React 项目中
- html - 如何在 flex div 中垂直居中字体真棒图标?
- jquery - Laravel - 我想在重定向到视图之前先显示我的 sweetalert
- javascript - D3.js 版本 5 图表转 PDF
- excel - Excel中两次之间的小时和分钟差异
- mongodb - 如何从未填充的模式(猫鼬)中删除引用的 ID?