关于SQL语句使用exists代替in ,我好像发现了更快的方式。

Pc498471249 2014-05-31 01:15:50

/***** SQL关联更新测试,Student表数据量200W,Score表数据量600W ****/

print 'update 关联更新'; --CPU 13353ms Time 7954ms ,Rows 3005139
set statistics time on
update [dbo].[Score] set [Score]=[Score]+2 from [dbo].[Score] as sc
inner join [dbo].[Student] as st on sc.StudentId=st.Id
where st.Age>50;
set statistics time off

print '-----------------------------------';

print 'in 更新' --CPU 13496ms Time 21101ms ,Rows 3005139
set statistics time on
update [dbo].[Score] set [Score]=[Score]+2 where StudentId in (select Id from [dbo].[Student] as s where s.Age>50)
set statistics time off

print '-----------------------------------';

print 'exists 更新' --CPU 13526ms Time 20989ms , Rows 3005139
set statistics time on
update [dbo].[Score] set [Score]=[Score]+2 where exists (select s.Id from [dbo].[Student] as s where s.Id=[dbo].[Score].StudentId and s.Age>50)
set statistics time off


看测试结果, 为什么exists没有比in明显的快???
...全文
529 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
极品老土豆 2014-05-31
  • 打赏
  • 举报
回复

/***************************************************************************************************************/
/*
1.很明显你的scord.id and student.id is the primary key,因此,in 是不考虑null情况的
                                                      ,and exists的优势因为primary key没有发挥出来
2.根据不同的sql版本优化器的优化是越来越优秀
3.对于你来说,你运行三次,都是相同状况下,对于,cpu,内存来说可不一定,快几百ms而已
4.第一种,索引查找表一边,第二种,第三种索引查找表N遍,第一种快是理所应当的
*/
/***************************************************************************************************************/



卖水果的net 版主 2014-05-31
  • 打赏
  • 举报
回复
LZ ,你跑一下 用 Student 中某个字段列 Score 中的某个字段,关联字段还有现有的条件。再看看结果。

34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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