【问题标题】:Strange behaviour in mysql json_extract with boolean带有布尔值的mysql json_extract中的奇怪行为
【发布时间】:2019-07-15 17:32:45
【问题描述】:

在这里,我首先展示一个布尔型 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'吗?我不喜欢这样,因为在不使用 coalesce 时同样的方法不起作用:

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 中得到“修补”,查询将被破坏。

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

【问题讨论】:

  • 我最终在相等 select coalesce(json_extract('{"a": true}', '$.a')=true, false) 之后进行了合并,但仍然可能有一种更优雅的方式来处理这个问题

标签: mysql json


【解决方案1】:

只要你合并json,就返回json

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

【讨论】:

  • 你也可以使用CAST(false AS JSON)作为COALESCE的参数。
  • 看起来它可以工作,但我不喜欢它看起来很hacky,另一种选择是做coalesce(json_contains('{"a": true}', 'true', '$.a'), false),它更干净并且永远不会比较非json的东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 2011-11-13
  • 1970-01-01
  • 2012-06-21
  • 2012-12-01
  • 1970-01-01
相关资源
最近更新 更多