关于SQL主键用int还是varchar类型的一个小测试

整理电脑文档时,看到以前做的关于int,varchar类型做主键的一个小测试,将代码又在sql里走了一遍,发现竟然区别不是那么明显,可能跟我的测试数据量比较小或者电脑配置有关吧。

先建立两张表,表结构一样,只是有一个是以int类型为主键,另一个是以varchar为主键。

然后向这两个表插入50万的数据量,也许是我的电脑配置比较低,插入50万数据用了5分钟。

代码
-- --------建立测试数据库及测试表---------------- 
--
drop database test 
create   database  Test 

use  Test 
create   table  intT( 
id 
int   not   null
name 
varchar ( 50 ), 
gid 
varchar ( 50

alter   table  intT  add   primary   key (id) 

create   table  varT( 
id 
varchar ( 50 not   null
name 
varchar ( 50 ), 
gid 
varchar ( 50

alter   table  varT  add   primary   key (id) 
-- --------分别对两个表插入W条数据------ 
declare   @start   datetime , @end   datetime  
select   @start = getdate () 
declare   @i   int  
select   @i = 0  
while   @i < 500000  
begin  
insert   into  intT(id,name,gid) values ( @i , @i , @i
select   @i = @i + 1  
end  
select   @end = getdate () 
select   @end - @start  

declare   @i   int  
select   @i = 0  
while   @i < 500000  
begin  
insert   into  varT(id,name,gid) values ( @i , @i , @i
select   @i = @i + 1  
end  

 插入数据后便可以进行不同查询条件的测试了。 

代码
-- --------测试查询------------------------------ 
--
---以主键作为查询条件----- 
declare   @d1   datetime , @d2   datetime  
select   @d1 = getdate () 
select   *   from  intT  where  id = 499900  
select   @d2 = getdate () 
select   @d2 - @d1  

declare   @d3   datetime , @d4   datetime  
select   @d3 = getdate () 
select   *   from  varT  where  id = ' 499900 '  
select   @d4 = getdate () 
select   @d4 - @d3

代码

-- ----不以主键作为查询条件------ 
declare   @d1   datetime , @d2   datetime  
select   @d1 = getdate () 
select   *   from  intT  where  id = 499900  
select   @d2 = getdate () 
select   @d2 - @d1  

declare   @d3   datetime , @d4   datetime  
select   @d3 = getdate () 
select   *   from  varT  where  id = ' 499900 '  
select   @d4 = getdate () 
select   @d4 - @d3

测试结果:50万的数据量下,int,varchar作为主键时,若以主键为查询条件,消耗时间几乎一样,但若以其他字段作为查询条件,两种主键的查询结果不太稳定,有时候是int快,有时候是varchar快。

总觉得测试的不够准确,数据量和语句上还需要修改,欢迎交流,赐教。

 

你可能感兴趣的:(sql,数据库,主键,类型,小测试)