来自:http://blog.sina.com.cn/s/blog_8a0c4f130100zaw2.htmlhtml
先谈谈in和exists的区别:spa
exists:存在,后面通常都是子查询,当子查询返回行数时,exists返回true。
select * from class where exists (select'x"form stu where stu.cid=class.cid)
当in和exists在查询效率上比较时,in查询的效率快于exists的查询效率
exists(xxxxx)后面的子查询被称作相关子查询, 他是不返回列表的值的.
只是返回一个ture或false的结果(这也是为何子查询里是select 'x'的缘由 固然也能够orm
select任何东西) 也就是它只在意括号里的数据能不能查找出来,是否存在这样的记录。
其运行方式是先运行主查询一次 再去子查询里查询与其对应的结果 若是存在,返回ture则输htm
出,反之返回false则不输出,再根据主查询中的每一行去子查询里去查询.blog
执行顺序以下:
1.首先执行一次外部查询
2.对于外部查询中的每一行分别执行一次子查询,并且每次执行子查询时都会引用外部查询中当索引
前行的值。
3.使用子查询的结果来肯定外部查询的结果集。
若是外部查询返回100行,SQL 就将执行101次查询,一次执行外部查询,而后为外部查询返回ci
的每一行执行一次子查询。form
in:包含
查询和全部女生年龄相同的男生
select * from stu where sex='男' and age in(select age from stu where sex='女')
in()后面的子查询 是返回结果集的,换句话说执行次序和exists()不同.子查询先产生结果集,
而后主查询再去结果集里去找符合要求的字段列表去.符合要求的输出,反之则不输出.class
not in和not exists的区别:
not in 只有当子查询中,select 关键字后的字段有not null约束或者有这种暗示时用not in,另外若是主查询中表大,子查询中的表小可是记录多,则应当使用not in,
例如:查询那些班级中没有学生的,
select * from class where cid not in(select distinct cid from stu)
当表中cid存在null值,not in 不对空值进行处理
解决:select * from class效率
where cid not in
(select distinct cid from stu where cid is not null)
not in的执行顺序是:是在表中一条记录一条记录的查询(查询每条记录)符合要求的就返回结果集,不符合的就继续查询下一条记录,直到把表中的记录查询完。也就是说为了证实找不到,因此只能查询所有记录才能证实。并无用到索引。
not exists:若是主查询表中记录少,子查询表中记录多,并有索引。
例如:查询那些班级中没有学生的,
select * from class2
where not exists
(select * from stu1 where stu1.cid =class2.cid)
not exists的执行顺序是:在表中查询,是根据索引查询的,若是存在就返回true,若是不存在就返回false,不会每条记录都去查询。之因此要多用not exists,而不用not in,也就是not exists查询的效率远远高与not in查询的效率。