博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在SQLite中使用索引优化查询速度
阅读量:4036 次
发布时间:2019-05-24

本文共 1514 字,大约阅读时间需要 5 分钟。

在进行多个表联合查询的时候,使用索引可以显著的提高速度,刚才用SQLite做了一下测试。

建立三个表:

create table t1
(id integer primary key,
num integer not null,
word1 text not null,
word2 text not null);
create table t2
(id integer primary key,
num integer not null,
word1 text not null,
word2 text not null);
create table t3
(id integer primary key,
num integer not null,
word1 text not null,
word2 text not null);

建立若干索引:
t1表:在num,word1,word2上有复合索引
t2表:在num,word1,word2上各有一个索引
t3表:在word1上有一个索引

create index idxT1 on t1(num,word1,word2);
create index idxT2Num on t2(num);
create index idxT2Word1 on t2(word1);
create index idxT2Word2 on t2(word2);
create index idxT3Word1 on t2(word1);

向三个表中各插入10000行数据,其中num项为随机数字,word1和word2中是英文单词,三个表中对应的num,word1和word2列中都包含有部分相同值,但是它们在表中出现的顺序不同。
速度测试结果:

1) select count(*) from t1,t3 where t1.word2=t3.word2;
很慢(t3.word2上没有索引)
2) select count(*) from t3,t1 where t1.word2=t3.word2;
很慢(t1.word2上没有独立索引)
3) select count(*) from t1,t2 where t1.word2=t2.word2;
很快(t2.word2上有索引)
4) select count(*) from t2,t1 where t1.word2=t2.word2;
很慢(t1.word2上没有独立索引)
5) select count(*) from t1,t2 where t1.num=t2.num;
很快(t2.num上有索引)
6) select count(*) from t2,t1 where t1.num=t2.num;
很快(t1的复合索引中,第一个列是num)
7) select count(*) from t1,t3 where t1.num=t3.num;
很慢(t3.num上没有索引)
8) select count(*) from t3,t1 where t1.num=t3.num;
很快(t1的复合索引中,第一个列是num)

结 论:在from子句后面的两个表中,如果第2个表中要查询的列里面带有索引,这个查询的速度就快,反之就慢。比如第三个查询,from后面的第2个表是 t2,t2在word2上有索引,所以这个查询就快,当输入SQL命令并回车后,查询结果就立即显示出来了,但是如果使用第4个查询命令(即把t1和t2 的位置互换),查询起来却用了1分零6秒。
可见索引的建立对于提高数据库查询的速度是非常重要的。

转载地址:http://jvcdi.baihongyu.com/

你可能感兴趣的文章
python单元测试unittest学习
查看>>
Errors running builder 'Validation' on project 'jumi_3.0'
查看>>
SpringMVC学习笔记
查看>>
springMVC如何接收前端传递的数组数据
查看>>
查看当前占用端口、关闭当前端口所暂用的进程
查看>>
Eclipse中有用的快捷键
查看>>
mysql将表字段信息拼接转换成实体类中的属性书写格式
查看>>
有return的情况下try catch finally的执行顺序
查看>>
input文本框中value值有双引号的问题
查看>>
java多线程简介
查看>>
web.xml配置加载顺序
查看>>
ServletContextListener使用详解
查看>>
UrlRewriteFilter使用说明
查看>>
java对redis的基本操作
查看>>
Java Math的 floor,round和ceil的使用
查看>>
通过url方式传递中文乱码解决办法
查看>>
Java的初始化机制、垃圾回收机制和内存分配机制
查看>>
MySQL5.6安装步骤(windows7/8_64位)
查看>>
FreeMarker基础配置
查看>>
Java中使用Jedis操作Redis
查看>>