2、not in 和not exists
not in 逻辑上不完全等同于not exists,如果你误用了not in,小心你的程序存在致命的bug。
请看下面的例子:
create table A1 (c1 int,c2 int); create table A2 (c1 int,c2 int); insert into A1 values(1,2); insert into A1 values(1,3); insert into A2 values(1,2); insert into A2 values(1,null); select * from A1 where c2 not in(select c2 from A2); -->执行结果:无(null) select * from A1 where not exists(select c2 from A2 where A2.c2=A1.c2); -->执行结果:1 3
正如所看到的,not in出现了不期望的结果集,存在逻辑错误。使用not in(它会调用子查询),而使用not exists(它会调用关联子查询)。如果子查询中返回的任意一条记录含有空值,则查询将不返回任何记录。如果子查询字段有非空限制,这时可以使用not in。
如果查询语句使用了not in,那么对内外表都进行全表扫描,没有用到索引;而not exists的子查询依然能用到表上的索引。所以无论哪个表大,用not exists都比not in 要快。
3、in 和 等于号(=)
select name from employee where name in('张三','李四','王五'); 与 select name from employee where name='张三' or name='李四' or name='王五'; 的结果是相同的。
4.exists防止插入重复记录
有时需要插入非重复记录,在Mysql中可以使用ignore关键字来忽略已有记录,但是其只能通过主键忽略,不能根据自定义条件忽略。
其语法为:insert ignore into tableName (column1,column2,……) values (value1,value2,……);
但是其他数据库不一定提供类似ignore关键字,所以可以使用exists条件句防止插入重复记录。
insert into A (name,age) select name,age from B where not exists (select 1 from A where A.id=B.id);
5.关于exists更多说明
exists用于检查子查询返回的结果集是否为空,该子查询实际上并不返回任何数据,而是返回值true或false。
语法: exists subQuery
参数: subQuery 是一个受限的 select 语句 (不允许有 compute 子句和 into 关键字)。
结果类型: boolean 如果子查询包含行,则返回 true ,否则返回 false 。
结论:select * from A where exists (select 1 from B where A.id=B.id);
一种通俗的可以理解为:将外查询表的每一行,代入内查询作为检验,如果内查询返回的结果集非空,则exists子句返回true,这一行方可作为外查询的结果行,否则不能作为结果。
--------以上sql内容根据网上提供的资料整理出的结果,均适用与Mysql、Sql
文章 书本笔记
摘录自身边朋友