MySQL提供了2种方法来检查boolean
列的真值,包括column_variable = true
和column_variable is true
。我创建了一个表,插入了几个值和尝试了一些select
陈述。结果如下:
首先我创建了这个表:
mysql> create table bool_test (
-> id int unsigned not null auto_increment primary key,
-> flag boolean );
Query OK, 0 rows affected (0.13 sec)
然后我插入了4行:
mysql> insert into bool_test(flag) values (true),(false),(9),(null);
mysql> select * from bool_test;
+----+------+
| id | flag |
+----+------+
| 1 | 1 |
| 2 | 0 |
| 3 | 9 |
| 4 | NULL |
以下是我在此表中触发的所有select
个查询:
mysql> select * from bool_test where flag;
+----+------+
| id | flag |
+----+------+
| 1 | 1 |
| 3 | 9 |
+----+------+
2 rows in set (0.49 sec)
mysql> select * from bool_test where flag = true;
+----+------+
| id | flag |
+----+------+
| 1 | 1 |
+----+------+
1 row in set (0.02 sec)
mysql> select * from bool_test where flag is true;
+----+------+
| id | flag |
+----+------+
| 1 | 1 |
| 3 | 9 |
+----+------+
2 rows in set (0.04 sec)
mysql> select * from bool_test where flag = false;
+----+------+
| id | flag |
+----+------+
| 2 | 0 |
+----+------+
1 row in set (0.01 sec)
mysql> select * from bool_test where flag is false;
+----+------+
| id | flag |
+----+------+
| 2 | 0 |
+----+------+
1 row in set (0.00 sec)
mysql> select * from bool_test where !flag;
+----+------+
| id | flag |
+----+------+
| 2 | 0 |
+----+------+
1 row in set (0.00 sec)
mysql> select * from bool_test where not flag;
+----+------+
| id | flag |
+----+------+
| 2 | 0 |
+----+------+
1 row in set (0.00 sec)
mysql> select * from bool_test where flag != true;
+----+------+
| id | flag |
+----+------+
| 2 | 0 |
| 3 | 9 |
+----+------+
2 rows in set (0.00 sec)
mysql> select * from bool_test where flag is not true;
+----+------+
| id | flag |
+----+------+
| 2 | 0 |
| 4 | NULL |
+----+------+
2 rows in set (0.00 sec)
mysql> select * from bool_test where flag != false;
+----+------+
| id | flag |
+----+------+
| 1 | 1 |
| 3 | 9 |
+----+------+
2 rows in set (0.04 sec)
mysql> select * from bool_test where flag is not false;
+----+------+
| id | flag |
+----+------+
| 1 | 1 |
| 3 | 9 |
| 4 | NULL |
+----+------+
3 rows in set (0.00 sec)
我的问题是:何时建议使用is
/ is not
,何时建议=
/ !=
使用true
/ { {1}}?哪一个与供应商无关?
答案 0 :(得分:27)
MySQL实际上在欺骗你。它doesn't have a boolean column type at all:
BOOL
,BOOLEAN
这些类型是
TINYINT(1)
的同义词。值为零 假。非零值被认为是真的:
此外,boolean literals are not such:
常量
TRUE
和FALSE
分别计算为1和0。
考虑到:
0
1
或BOOLEAN
我的结论是:
WHERE IS flag
或WHERE flag
,因为=
根本无法正常使用。哪一个,可能是一个偏好问题。编辑:如果跨平台是必须的,我会这样做:
WHERE flag=0
WHERE flag<>0
我确定我们已经做了很多次。
答案 1 :(得分:3)
如果flag
列已建立索引并且所有值均为0或1,则where flag = true
比where flag is true
快得多。
在我们的测试过程中,is true
导致了“全表扫描”,并且花费了1.121秒,而= true
被执行了“键查找”,仅花费了0.167秒。该表大约有300万行。