一. 表结构和初始化数据
- 表结构
- 初始化数据
insert into test_in(name, hobby, sex, school) values('张一','打球',1,'北京大学');
insert into test_in(name, hobby, sex, school) values('张二','看书',null,'清华大学');
insert into test_in(name, hobby, sex, school) values('张三','游泳',1,null);
insert into test_in(name, hobby, sex, school) values('张四','跳绳',1,'大连大学');
insert into test_in(name, hobby, sex, school) values('张五','健身',2,'青岛大学');
insert into test_in(name, hobby, sex, school) values('张六','学习',2,'吉林大学');
- 查询结果:
select * from test_in;
二. SQL中in的使用
- 正常in的使用:
select * from test_in where sex in (1);
- 有null值的in使用:
select * from test_in where sex in (1,null);
划重点:SQL中使用in时,会忽略null值的记录,即不会查询出列值为null的数据。
三. SQL中not in的使用
- 正常not in的使用:
select * from test_in where sex not in (1);
划重点:SQL中使用not in时,如果 not in后面的选项中没有null,只会查询从列值不为空的列中过滤,即会过滤掉列值为null的数据。
- 有null值的not in的使用:
select * from test_in where sex not in (1, null);
划重点:SQL中使用not in时,如果not in后面的选项中有null,则不会查询出来任何数据。因为sql语句本身直接返回false,所以使用not in时候,要保证not in后的条件值不会出现null,不然可能会出现意想不到的情况。
参考资料