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
为什么放置 0
或 false
会使查询 return 所有行?
数据是什么并不重要,但这里有一个示例:
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
字面上是整数1,false
是整数0。这是non-standard,与其他[=29=不相似] 实现,但这是 MySQL 的工作方式。
mysql> select true, false;
+------+-------+
| true | false |
+------+-------+
| 1 | 0 |
+------+-------+
当您将一个整数与一个字符串进行比较时,该字符串会被转换为其整数值,该整数值基于该字符串中的任何前导数字字符。如果它没有前导数字,则整数值为 0。
所以你在比较 0 = 1
和 0 = 0
:
mysql> select 'x' = 1, 'x' = 0;
+---------+---------+
| 'x' = 1 | 'x' = 0 |
+---------+---------+
| 0 | 1 |
+---------+---------+
所有 x
没有前导数字的行的计算结果为 0,因此等于 false
。
在以下查询中:
select count(1) from main_territory where code = true
union all
select count(1) from main_territory where code = false;
-------------------------------------------------------------------
count(1)
0
250
为什么放置 0
或 false
会使查询 return 所有行?
数据是什么并不重要,但这里有一个示例:
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
字面上是整数1,false
是整数0。这是non-standard,与其他[=29=不相似] 实现,但这是 MySQL 的工作方式。
mysql> select true, false;
+------+-------+
| true | false |
+------+-------+
| 1 | 0 |
+------+-------+
当您将一个整数与一个字符串进行比较时,该字符串会被转换为其整数值,该整数值基于该字符串中的任何前导数字字符。如果它没有前导数字,则整数值为 0。
所以你在比较 0 = 1
和 0 = 0
:
mysql> select 'x' = 1, 'x' = 0;
+---------+---------+
| 'x' = 1 | 'x' = 0 |
+---------+---------+
| 0 | 1 |
+---------+---------+
所有 x
没有前导数字的行的计算结果为 0,因此等于 false
。