两个大表嵌套查询, 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)
要做这样的查询: 在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)
...全文
相关推荐
数据库嵌套查询
数据库嵌套查询
oracle sql优化
oracle sql优化
优化数据库的方法及SQL语句优化的原则
优化数据库的方法: 1、关键字段建立索引。 2、使用存储过程,它使SQL变得更加灵活和高效。 3、备份数据库和清除垃圾数据。 4、SQL语句语法的优化。(可以用Sybase的SQL Expert,可惜我没找到unexpired的序列号) 5、清理删除日志。 ...........
高级数据库相关知识总结
是对高级数据库技术主要知识点的总结,主要包括性能设计的原则、索引的使用、分区等。
Mysql数据库性能优化之子查询
主要介绍了Mysql数据库性能优化之子查询的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下


