sqlite 索引优化方法
在进行多个表联合查询的时候,使用索引可以显著的提高速度,刚才用SQLite做了一下测试。 (id integer primary key, num integer not null, word1 text not null, word2 text not null); create table t2 (id integer primary key, word2 text not null); create table t3 (id integer primary key, word2 text not null);
create index idxT2Num on t2(num); create index idxT2Word1 on t2(word1); create index idxT2Word2 on t2(word2); create index idxT3Word1 on t2(word1);
很慢(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)
1、索引可以大大加快查询速度 2、当有交叉查询时,from a,b两个表,取决于b表是否有索引 3、当b上的索引不是独立索引时,查询速度取决于非独立索引的第一个字段
在from子句后面的两个表中,如果第2个表中要查询的列里面带有索引,这个查询的速度就快,反之就慢。比如第三个查询,from后面的第2个表是 t2,t2在word2上有索引,所以这个查询就快,当输入SQL命令并回车后,查询结果就立即显示出来了,但是如果使用第4个查询命令(即把t1和t2 的位置互换),查询起来却用了1分零6秒。 可见索引的建立对于提高数据库查询的速度是非常重要的。 更多关于SQLite查询优化的知识可以参考《Chris Newman》写的《SQLite》一书的第四章:《Query Optimization》 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |