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

yy00915132 yy00915132 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
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)
...全文
评论 2
收藏 已收藏
分享
返回顶部
yy00915132
MySQL 57,063 成员 56,760 内容