首页 > 数据库技术 > 详细

MS Sql Service 记一次in查询的优化

时间:2020-05-09 17:35:13      阅读:58      评论:0      收藏:0      [点我收藏+]

sql临时表使用方法

创建

select [字段1,字段2,...,] into #TempTableName from table (#表示局部,##标签全局)

删除

drop table #TempTableName

 

实例:

select table1.* from table1 as table1 WITH (NOLOCK)

left join table2 as table2 WITH (NOLOCK)

on table1.number = table2.number

where table1.number in (‘1‘,‘2‘,‘3‘,‘4‘,.......);

 

当table1与table2都为大表,数据在千万级,这样的查询效率会急剧下降。

 

其中一个优化方式,可以使用临时表

SELECT table1.number INTO #temp FROM table1 as table1 WHERE table1.number in (‘1‘,‘2‘,‘3‘,‘4‘,.......);

 

select table1.* from table1 as table1 WITH (NOLOCK)

left join table2 as table2 WITH (NOLOCK)

on table1.number = table2.number

inner join #temp as temptable

on temptable.number = table1.number;

或者

where table1.number in (select number from #temp);//用到table1的索引,如果table1比#temp数据大,效率高

或者

where exists(select number from #temp where number=table1.number)//用到#temp的索引,如果table1比#temp数据大,效率低

 

drop table #temp;

 

这样的修改把in方式变成临时标签join的方式,能提高查询效率。

 

MS Sql Service 记一次in查询的优化

原文:https://www.cnblogs.com/jeffhong99/p/12858728.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!