繁体   English   中英

Mysql 等于 false 或 true

[英]Mysql equality against false or true

在以下查询中:

select count(1) from main_territory where code = true
union all
select count(1) from main_territory where code = false;

-------------------------------------------------------------------
count(1)
0
250

为什么输入0false会使查询返回所有行?

数据是什么并不重要,但这里有一个示例:

CREATE TABLE z_tmp (x varchar(11));
insert into z_tmp values ('x'); -- note this is not a Boolean
select count(1) from z_tmp where x=true union all select count(1) from z_tmp where x=false;

注意:我使用的是mysql5.7。

在 MySQL 中, true字面上是 integer 1, false是 integer 0。这是非标准的,与其他一些 SQL 实现不相似,但这是 MySQL 的工作方式。

mysql> select true, false;
+------+-------+
| true | false |
+------+-------+
|    1 |     0 |
+------+-------+

当您将 integer 与字符串进行比较时,该字符串会转换为其 integer 值,该值基于字符串中的任何前导数字字符。 如果它没有前导数字,则 integer 值为 0。

所以你比较0 = 10 = 0

mysql> select 'x' = 1, 'x' = 0;
+---------+---------+
| 'x' = 1 | 'x' = 0 |
+---------+---------+
|       0 |       1 |
+---------+---------+

x没有前导数字的所有行都评估为 0,因此等于false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM