2016-07-08 31 views
2

表架構不使用索引這樣的:爲什麼加入搜索SQLite中

sqlite> CREATE TABLE tbl1(seq int, companyid int, field1 int NULL, field2 int NULL, field3 int NULL, field4 int NULL, field5 int NULL); 
sqlite> create index tbl1_idx on tbl1(seq); 
sqlite> CREATE TABLE tbl2(symbolid int, relatedcompanyid char(64), value char(64), field1 int NULL, field2 int NULL, field3 int NULL, field4 int NULL, field5 int NULL); 
sqlite> create index tbl2_idx on tbl2(relatedcompanyid); 

sqlite> explain query plan select tbl2.value from tbl2, tbl1 where tbl1.seq = 100 and tbl1.companyid = tbl2.relatedcompanyid; 
0|1|TABLE tbl1 WITH INDEX tbl1_idx 
1|0|TABLE tbl2 

爲什麼第二步不會使用索引tbl2_idx,因爲companyid在第一步中已經得到了什麼?如果使用索引,這個搜索將會快得多 如何優化這個sql查詢?

+0

如果您正在運行sqlite 3.2.3+也許先嚐試'ANALYZE'? – woot

+0

我試過了,怎麼解釋ANALYZE的結果? – wushiqi

回答

1

tbl1.companyidtbl2.relatedcompanyid具有不同affinitiesint是NUMBER,char(64)是TEXT),所以在某些情況下,這兩列might require type conversions比較值,因此此查找不能與索引進行優化。

0

謝謝。這是非常有幫助的

CREATE TABLE tbl2(symbolid int, relatedcompanyid int, value char(64), field1 int NULL, field2 int NULL, field3 int NULL, field4 int NULL, field5 int NULL); 
create index tbl2_idx on tbl2(relatedcompanyid); 
explain query plan select tbl2.value from tbl2, tbl1 where tbl1.seq = 100 and tbl1.companyid = tbl2.relatedcompanyid; 
0|0|1|SEARCH TABLE tbl1 USING INDEX tbl1_idx (seq=?) 
0|1|0|SEARCH TABLE tbl2 USING INDEX tbl2_idx (relatedcompanyid=?)