SQL查询效率:100w数据查询只需要1秒钟
创始人
2024-07-25 07:00:32
0

关于SQL查询效率,100w数据,查询只要1秒,您相信吗?大家都知道,现在的数据库储存容量是越来越大,数据库的查询效率可能在一定程度上有所降低,现在的技术是飞速发展进步,实现100w数据查询只需要1秒钟已经是可能的啦,下文中就为大家介绍这种方法,希望对大家有帮助。

机器情况:

p4: 2.4

内存: 1 G

os: windows 2003

数据库:

SQL Server 2000

目的: 查询性能测试,比较两种查询的性能

SQL查询效率 step by step

 setp 1.

建表

create table t_userinfo

(

userid int identity(1,1) primary key nonclustered,

nick varchar(50) not null default '',

classid int not null default 0,

writetime datetime not null default getdate()

)

go

建索引

create clustered index ix_userinfo_classid on t_userinfo(classid)

go

step 2.

declare @i int

declare @k int

declare @nick varchar(10)

set @i = 1

while @i<1000000

begin

set @k = @i % 10

set @nick = convert(varchar,@i)

insert into t_userinfo(nick,classid,writetime) values(@nick,@k,getdate())

set @i = @i + 1

end

耗时 08:27 ,需要耐心等待

step 3.

select top 20 userid,nick,classid,writetime from t_userinfo

where userid not in

(

select top 900000 userid from t_userinfo order by userid asc

)

耗时 8 秒 ,够长的

step 4.

select a.userid,b.nick,b.classid,b.writetime from

(

select top 20 a.userid from

(

select top 900020 userid from t_userinfo order by userid asc

) a order by a.userid desc

) a inner join t_userinfo b on a.userid = b.userid

order by a.userid asc

耗时 1 秒,太快了吧,不可以思议

step 5

where 查询

select top 20 userid,nick,classid,writetime from t_userinfo

where classid = 1 and userid not in

(

select top 90000 userid from t_userinfo

where classid = 1

order by userid asc

)

耗时 2 秒


step 6

where 查询

select a.userid,b.nick,b.classid,b.writetime from

(

select top 20 a.userid from

(

select top 90000 userid from t_userinfo

where classid = 1

order by userid asc

) a order by a.userid desc

) a inner join t_userinfo b on a.userid = b.userid

order by a.userid asc

查询分析器显示不到 1 秒.

查询效率分析:

子查询为确保消除重复值,必须为外部查询的每个结果都处理嵌套查询。在这种情况下可以考虑用联接查询来取代。

如果要用子查询,那就用EXISTS替代IN、用NOT EXISTS替代NOT IN。因为EXISTS引入的子查询只是测试是否存在符合子查询中指定条件的行,效率较高。无论在哪种情况下,NOT IN都是***效的。因为它对子查询中的表执行了一个全表遍历。

建立合理的索引,避免扫描多余数据,避免表扫描!

几百万条数据,照样几十毫秒完成查询。

【编辑推荐】

  1. 提高MySQL数据库查询效率的技巧(三)
  2. 如何在MySQL查询结果集中得到记录行号
  3. 实例讲解如何配置MySQL数据库主从复制

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
各种千兆交换机的数据接口类型详... 千兆交换机有很多值得学习的地方,这里我们主要介绍各种千兆交换机的数据接口类型,作为局域网的主要连接设...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
Windows恶意软件20年“... 在Windows的早期年代,病毒游走于系统之间,偶尔删除文件(但被删除的文件几乎都是可恢复的),并弹...
规避非法攻击 用好路由器远程管... 单位在市区不同位置设立了科技服务点,每一个服务点的员工都通过宽带路由器进行共享上网,和单位网络保持联...
范例解读VB.NET获取环境变... VB.NET编程语言的使用范围非常广泛,可以帮助开发人员处理各种程序中的需求,而且还能对移动设备进行...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...