- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
如何提高查询性能
减少IO
减少CPU运算
使用内存
索引、提示、查询优化器和执行计划
提示是指定的强制选项或策略,由 SQL Server 查询处理器针对 SELECT、INSERT、UPDATE 或 DELETE 语句执行。
提示将覆盖查询优化器可能为查询选择的任何执行计划。
因为 SQL Server 查询优化器通常会为查询选择最优执行计划,因此我们建议,只有在万般无奈的情况下才由经验丰富的开发人员和数据库管理员使用 join_hint、query_hint 和 table_hint。
--创建表Users 并主键约束聚集索引
Create table Users
(
UserID int identity,
UserName nvarchar(50),
Age int,
Gender bit,
CreateTime datetime,
constraint PK_UserID primary key clustered (UserID)
)
--在UserName创建非聚集索引IX_UserName
create index IX_UserName on Users(UserName)
--插入示例数据
insert into Users(UserName,Age,Gender,CreateTime)
select NBob,20,1,2012-5-1
union all
select NJack,23,0,2012-5-2
union all
select NRobert,28,1,2012-5-3
union all
select NJanet,40,0,2012-5-9
union all
select NMichael,22,1,2012-5-2
union all
select NLaura,16,1,2012-5-1
union all
select NAnne,36,1,2012-5-7
--查询1:
select UserID,UserName from Users with(index(IX_UserName))
where UserName=Robert
select UserID,UserName from Users
where UserName=Robert
--查询2:
select UserID,UserName,Age from Users with(index(IX_UserName))
where UserName=Robert
select UserID,UserName,Age from Users
where UserName=Robert
--查询3
select * from Users
with(index(IX_UserName))
where UserName=Robert
select * from users
where UserName=Robert
如何书写高效SQL
需要多少检索多少
select * from users;(聚集索引中检索数据)
select userid,username from users; (非聚集索引中检索数据,io少) 快
where条件中不要使用 or
where id=1 or id=5
?
Select 1 id
Union all
Select 2 id
?
避免使用 like ‘%abcd%’
select top 10 UserID, CreateTime
from Users
where UserName like %abcd%
select top 10 UserID,CreateTime
from Users
where UserName like abcd%
select top 10 UserID, CreateTime
from Users
where UserName like %abcd% and
CreateTime =2010-01-31 12:12:16.297
如不能避免,一定要在其它列上有范围的限定
分词也个解决
CONTAINS(names,免考*)
避免或简化order by
索引列上order by
建议在代码内部排序
改写 in
select userid,username
from users
where UserID in (select UserID from orderform where OrderTpye=5)
select a.userid,a.username
from users a inner join orderform b on a.userid=b.userid
where
文档评论(0)