从100万条数据中找出年龄最大的人员
今天在网上看到这样一篇文章,就是关于从100万条人员信息中选择年龄最大的人员信息的查询问题。
我觉得很有收藏价值,所以在这整理了一下,与大家分享
首先创建一张人员信息表:
create table person
(
id int identity(1,1) not null,
pid varchar(18) not null,
md varchar(11) not null,
age int
)
go
declare @pid varchar(15)
declare @age int
declare @mb varchar(11)
declare @count int
set @count = 0
--插入100万条随机的记录
while(@count < 1000000)
begin
--生成随机的PID
select @pid=substring(cast(rand() as varchar(20)),3,6)+
substring(cast(rand() as varchar(20)),3,6)+substring(cast(rand() as varchar(20)),3,6)
--生成随机的MB
select @mb=substring(cast(rand() as varchar(20)),3,6)+
substring(cast(rand() as varchar(20)),3,5)
--生成随机的AGE
select @age = cast (rand() * 100 as int)
--将生成的随机数据插入表
insert into person
values ( @pid, @mb,@age)
set @count = @count + 1
end
已经创建了人员信息表,并且在其中随机的插入了100万条数据
下面有两种查询方式
我们在这做个比较
方法一:
DECLARE @BD DATETIME
DECLARE @ED DATETIME
SET @BD = GETDATE()--执行之前记录时间
SELECT TOP 1 * FROM PERSON ORDER BY AGE DESC
SET @ED = GETDATE()--执行之后记录时间
SELECT datediff(millisecond,@BD,@ED)--用毫秒的方法显示执行时间。
解决办法:
为person表的age这一列创建索引
create nonclustered index ix_age
on person(age)
on person(age)
/*清空缓存*/
DBCC FREEPROCCACHE --清空SQL缓存
DBCC DROPCLEANBUFFERS
DBCC DROPCLEANBUFFERS
方法二:子查询
DECLARE @BD DATETIME
DECLARE @ED DATETIME
SET @BD = GETDATE()
select * from person where age =(
select max(age) from person )
SET @ED = GETDATE()
SELECT datediff(millisecond,@BD,@ED)
方法一的查询效率明显低于方法二
浙公网安备 33010602011771号