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

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

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

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

ExpandedBlockStart.gif 代码
-- --------建立测试数据库及测试表---------------- 
--
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  

 

 

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

 

ExpandedBlockStart.gif 代码
-- --------测试查询------------------------------ 
--
---以主键作为查询条件----- 
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

 

 

image 

image

ExpandedBlockStart.gif 代码
-- ----不以主键作为查询条件------ 
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

 

 

image

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值