两个大表嵌套查询, exists 跟 in 的优化问题
student 表跟 schedule 表, 两个表都挺大, 大小相似.
要做这样的查询: 在schedule 中搜索满足一定条件的student 的schedule
用 in 大约83秒, 用exists 也是80秒左右. 但是如果我先手动执行 子查询, 然后子查询输入到括号里, 那时间是3秒+0.1秒, 会快很多.
之前认识是: 如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in, 但是当两个表都大, 而子查询其实执行一次就够了, 那应该怎么写呢? 非常感谢了.
in 的语句:
select * form schedule sch where sch.att1="123" and sch.att2 = "234" and sch.stu_id in ( select stu.stu_id from student stu where stu.score >123 and stu.money=123)
exists 的sql:
select * form schedule sch where sch.att1="123" and sch.att2 = "234" and exists ( select stu.stu_id from student stu where stu.score >123 and stu.money=123 and sch.stu_id = stu.stu_id);
我先手动执行 子查询, 然后子查询输入到括号里:
就是: 先执行" select stu.stu_id from student stu where stu.score >123 and stu.money=123" ,结果是1,2,3,4,5
再执行 "select * form schedule sch where sch.att1="123" and sch.att2 = "234" and sch.stu_id in (1,2,3,4,5)