首页 > 解决方案 > 带有布尔值的mysql json_extract中的奇怪行为

问题描述

在这里,我首先展示一个布尔 json_extract 的原始结果。然后我将它与真实进行比较。然后在合并后再次比较为真。

MySQL [(none)]> select json_extract('{"a": true}', '$.a');
+------------------------------------+
| json_extract('{"a": true}', '$.a') |
+------------------------------------+
| true                               |
+------------------------------------+
1 row in set (0.00 sec)

MySQL [(none)]> select json_extract('{"a": true}', '$.a')=true;
+-----------------------------------------+
| json_extract('{"a": true}', '$.a')=true |
+-----------------------------------------+
|                                       1 |
+-----------------------------------------+
1 row in set (0.01 sec)

MySQL [(none)]> select coalesce(json_extract('{"a": true}', '$.a'), 'false')=true;
+------------------------------------------------------------+
| coalesce(json_extract('{"a": true}', '$.a'), 'false')=true |
+------------------------------------------------------------+
|                                                          0 |
+------------------------------------------------------------+
1 row in set (0.01 sec)

如您所见,合并后 MySQL 不知道我在那里处理 json 的东西。

问题:我应该如何为我的 json_extract 提供合并后备,同时能够将值与 true 进行比较?我应该使用 json 字符串select coalesce(json_extract('{"a": true}', '$.a'), 'false')='true'吗?我不喜欢这样,因为不使用合并时相同的方法不起作用:

MySQL [(none)]> select json_extract('{"a": true}', '$.a')='true';
+-------------------------------------------+
| json_extract('{"a": true}', '$.a')='true' |
+-------------------------------------------+
|                                         0 |
+-------------------------------------------+
1 row in set (0.00 sec)

MySQL [(none)]> select coalesce(json_extract('{"a": true}', '$.a'), 'false')='true';
+--------------------------------------------------------------+
| coalesce(json_extract('{"a": true}', '$.a'), 'false')='true' |
+--------------------------------------------------------------+
|                                                            1 |
+--------------------------------------------------------------+
1 row in set (0.00 sec)

如果有人查看这些查询,他们会认为这是一个错误,并且如果在未来版本的 mysql 中这得到“修补”,查询将被破坏。

实现此合并功能的正确方法是什么?

标签: mysqljson

解决方案


json只要你合并就回退json

select cast(coalesce(json_extract('{"a": true}', '$.a'), 'false') as json)=true;

在此处输入图像描述


推荐阅读