简体   繁体   English

Mysql 等于 false 或 true

[英]Mysql equality against false or true

In the following query:在以下查询中:

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

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

Why does putting 0 or false make the query return all rows?为什么输入0false会使查询返回所有行?

It doesn't matter what the data is, but here's a sample:数据是什么并不重要,但这里有一个示例:

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;

Note: I'm using mysql5.7.注意:我使用的是mysql5.7。

In MySQL, true is literally the integer 1 and false is the integer 0. This is non-standard and not similar to some other SQL implementations, but this is the way MySQL works.在 MySQL 中, true字面上是 integer 1, false是 integer 0。这是非标准的,与其他一些 SQL 实现不相似,但这是 MySQL 的工作方式。

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

When you compare an integer to a string, the string is cast to its integer value, which is based on any leading digit characters in the string.当您将 integer 与字符串进行比较时,该字符串会转换为其 integer 值,该值基于字符串中的任何前导数字字符。 If it has no leading digits, the integer value is 0.如果它没有前导数字,则 integer 值为 0。

So you're comparing 0 = 1 and 0 = 0 :所以你比较0 = 10 = 0

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

All the rows where x has no leading digits evaluate as 0, and therefore are equal to false . x没有前导数字的所有行都评估为 0,因此等于false

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

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