两个大表嵌套查询, exists 跟 in 的优化问题

yy00915132 2015-05-28 05:49:31
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)
...全文
549 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ACMAIN_CHM 2015-05-28
  • 打赏
  • 举报
回复
用explain select 和 show index 来检查设计执行方案。
yy00915132 2015-05-28
  • 打赏
  • 举报
回复
找到方案了: select * form schedule sch, ( select stu_id from student where score >123 and money=123) stuTemp where sch.att1="123" and sch.att2 = "234" and sch.stu_id =stuTemp.stu_id

56,675

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧