null值的一些测试
演示表
drop table if exists p;
CREATE TABLE `p` (
`name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `p` VALUES ('刘备');
INSERT INTO `p` VALUES ('孙权');
INSERT INTO `p` VALUES ('曹操');
INSERT INTO `p` VALUES (NULL);
drop table if exists p2;
CREATE TABLE `p2` (
`name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
结论
- 任何值都不会在空集合中。任何值 not in 空集 === true ,任何值 in 空集 === false
- 如果运算结果为null,则被当作false
# 参与逻辑运算,null被当作false
select * from p where null;
select * from p where false;
select * from p where true;
#任何值(包括null) not in 空集 恒等于 true
select name from p
where p.name not in (select name from p2);
#任何值(包括null) in 空集 恒等于 false
select name from p
where p.name in (select name from p2);
#结论:任何值都不会在空集合中
现象
select 'a' not in ('a', null); # 0
select 'b' not in ('a', null); # null
select null not in ('a', null); # null
select 'a' in ('a', null); # 1
select 'b' in ('a', null); # null
select null in ('a', null); # null
推测
select null not in ('a', null);
# !(null = 'a' and null = null)
# !(null and null)
# null
select null in ('a', null);
# null = 'a' or null = null
# null or null
# null
select 'a' not in ('a', null); #0
# !('a' = 'a' or 'a' = null)
# !(true or null)
# false
select 'a' in ('a', null); #1
# 'a' = 'a' or 'a' = null
# true or null
# true
select 'b' not in ('a', null);
# !('b' = 'a' and 'b' = null)
# !(false and null)
# null
select 'b' in ('a', null);
# 'b' = 'a' or 'b' = null
# false or null
# null
在表1但是不在表2有null值的情况
# 当2个表中都含有null值时的现象。想求出在表1但是不在表2的记录。
select name from p where p.name not in (select name from p3);
select name from p where p.name not in ('曹操', null);
select name from p where p.name in (select name from p3);
select name from p where p.name in (null, '曹操');
在表1但是不在表2(没有null值但是表可能为空)
null值参与运算
# null值的运算,只有 null or true的结果不是null。
select null = null;
select null != null;
select null and true;
select 1= null;
select 1 != null;
select 1 > null;
select null or false;
select null or null;
select null in (null);
select null not in (null);
select !null;
select count(1) from (select null = null) as T;
# 注意只有这几种不会得到null
select null or true; #1
select null is null; #1
select null is not null; #0