NULL 的判等,不能用 =
,而应该用 is
。判不等,不能用!=
,而应该用is not
。
示例 | 执行结果 |
---|---|
select null is null; | 1 |
select null = null; | null |
select 1 = 1; | 1 |
select 1 = 0; | 0 |
select 1 != null; | null |
select 1 is not null; | 1 |
select null is not null; | 0 |
执行结果中,1 是 true,0是false,null代表未知。
可以这样理解,未知是未知,但两个未知不相等。
再用一个真实的表做例子:
USE test;
CREATE TABLE `test_table` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name1` varchar(32) DEFAULT NULL COMMENT '名字1',
`name2` varchar(32) DEFAULT NULL COMMENT '名字2',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
插入数据:
insert into test_table(name1, name2) values('letian', 'letian');
insert into test_table(name1, name2) values('letian', 'letianbiji');
insert into test_table(name1, name2) values('letian', null);
insert into test_table(name1, name2) values(null, null);
查询:
mysql> select * from test_table;
+----+--------+------------+
| id | name1 | name2 |
+----+--------+------------+
| 1 | letian | letian |
| 2 | letian | letianbiji |
| 3 | letian | <null> |
| 4 | <null> | <null> |
+----+--------+------------+
mysql> select * from test_table where name1=name2;
+----+--------+--------+
| id | name1 | name2 |
+----+--------+--------+
| 1 | letian | letian |
+----+--------+--------+
mysql> select * from test_table where name1 != name2;
+----+--------+------------+
| id | name1 | name2 |
+----+--------+------------+
| 2 | letian | letianbiji |
+----+--------+------------+
mysql> select * from test_table where name2 = null;
无结果
mysql> select * from test_table where name2 is null;
+----+--------+--------+
| id | name1 | name2 |
+----+--------+--------+
| 3 | letian | <null> |
| 4 | <null> | <null> |
+----+--------+--------+