这是个很很很基础的知识,但是自己总是会忘,故记下来,免得每次百度。。。
话不多说,看代码
- IN:
select * from student
where student_id in (
select student_id from subject
)
in 执行流程:
1.首先执行子查询:
select student_id from subject
2.将1中的查询结果与student表做笛卡尔积
3.去除student.student_id与subject.student_id 不相等的行。最后就得到数据了。
从上述流程我们很容易得出结论:用in时,我们内表数据量应该小
- EXISTS
select … from …exists(….)
注:exists的返回结果是bool型,只有true或者false,要么全查要么不查
select * from student
where exists(
select student_id from subject
where student.student_id = subject.student_id
)
以上sql的查询结果与用in的查询结果一致。
exists 的执行流程:
1.查询主查询的表
select * from student
2.根据1中查询的结果来判断where后的条件是否成立。
exists(
select student_id from subject
where student.student_id = subject.student_id
)
由上述流程我们又可以很容易的得出,用exists时,外表要小些比较好。
拓展:not in 和not exists
如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;而not extsts 的子查询依然能用到表上的索引。所以无论那个表大,用not exists都比not in要快。
总结,sql查询万变不离其宗,先查小表,判读条件尽量去除多的数据。