国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 開(kāi)發(fā) > 綜合 > 正文

建索引(尤其是主鍵)時(shí)請(qǐng)注意索引列順序

2024-07-21 02:43:57
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友
在創(chuàng)建主鍵或其它索引時(shí),SQL Server總是自動(dòng)將字段的順序設(shè)置為升序排列;升序是默認(rèn)設(shè)置,是為了保持與 SQL Server 早期版本的兼容性。建索引時(shí)索引列的順序應(yīng)該按照常用查詢(xún)中的排序方式排序。

我們做個(gè)試驗(yàn)創(chuàng)建一個(gè)表,其中主鍵上的聚集索引按照id倒敘排列,然后分別倒敘順序select數(shù)據(jù),比較select的時(shí)間:

+測(cè)試代碼

if object_id('test_indexorder','U') is not null

begin

truncate table test_indexorder

drop table test_indexorder

end

go

create table test_indexorder

(

id int identity(1,1) not null,

name varchar(20) not null,

content varchar(50) not null,

co1 varchar(50),

co2 varchar(50),

co3 varchar(50),

co4 varchar(50),

co5 varchar(50),

constraint pk_testorder PRimary key clustered(

id desc

)

)

go

--insert 1000000 條數(shù)據(jù)

set nocount on;

declare @t datetime;

set @t = getdate();

DECLARE @cn int;

set @cn = 1000000;

while(@cn > 0)

begin

insert into test_indexorder(name,content,co1,co2,co3,co4,co5)

VALUES(

'name' + cast(@cn as varchar(10)),

cast(newid() as varchar(50)),

cast(newid() as varchar(50)),

cast(newid() as varchar(50)),

cast(newid() as varchar(50)),

cast(newid() as varchar(50)),

cast(newid() as varchar(50)));

set @cn = @cn -1;

end

print '插入時(shí)間(毫秒):';

print datediff(millisecond,@t,getdate());

set nocount off;

GO

checkpoint

dbcc freeproccache

dbcc dropcleanbuffers

GO

go

set nocount on;

declare @t datetime;

set @t = getdate();

with t_rn as (

select *,rn = ROW_NUMBER() OVER (ORDER BY id desc) FROM test_indexorder

)

SELECT id,name,content,co1,co2,co3,co4,co5 from t_rn WHERE rn between 19007 and 19057;

print '查詢(xún)時(shí)間(毫秒)'

print datediff(millisecond,@t,getdate())

set @t = getdate();

with t_rn as (

select *,rn = ROW_NUMBER() OVER (ORDER BY id asc) FROM test_indexorder

)

SELECT id,name,content,co1,co2,co3,co4,co5 from t_rn WHERE rn between 17007 and 17057;

print '查詢(xún)時(shí)間(毫秒)'

print datediff(millisecond,@t,getdate())

set nocount off;

以下是查詢(xún)時(shí)間結(jié)果

查詢(xún)時(shí)間(毫秒)

393

查詢(xún)時(shí)間(毫秒)

606

按照和索引相同順序從100萬(wàn)條數(shù)據(jù)中取50條時(shí)需要393毫秒,相反順序時(shí)需要606毫秒。造成的性能影響還是挺大的。

結(jié)論:

在建索引時(shí)要考慮常用查詢(xún)的排序方式,在建主鍵時(shí)要特別注意,因?yàn)閟ql server會(huì)自動(dòng)按照升序來(lái)建,這時(shí)候如果您的查詢(xún)多數(shù)用主鍵列倒敘排列,記得要修改一下默認(rèn)的設(shè)置。


發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 岐山县| 鞍山市| 安仁县| 临泉县| 囊谦县| 靖远县| 广水市| 固安县| 美姑县| 宝兴县| 兴城市| 寿阳县| 普兰店市| 富裕县| 武汉市| 准格尔旗| 吉水县| 蓬莱市| 镇赉县| 富平县| 穆棱市| 横峰县| 武宣县| 阆中市| 新营市| 庄河市| 股票| 汉源县| 大竹县| 璧山县| 乌拉特后旗| 卓尼县| 随州市| 客服| 任丘市| 华阴市| 镶黄旗| 四子王旗| 新民市| 清河县| 新乐市|