sqlite3订单需要时间

时间:2013-01-05 09:27:58

标签: python sql select sqlite sql-order-by

我在sqlite3 db中有表位于内存映射分区。我有这个查询计划的select语句:

sqlite3> EXPLAIN QUERY PLAN SELECT sst.prefix, 0 AS pb, sst.rate, 
sst.rate_n, sst.interval_1, sst.interval_n
FROM sch AS sst
WHERE
sst.i_workbook_id = 989 AND 
sst.prefix IN ('', '1', '19', '191', '1919', '19198') AND 
sst.activation_date <= DATETIME('now') AND 
(sst.expiration_date > DATETIME('now') OR sst.expiration_date IS NULL) AND
sst.start_time <= TIME('now') AND 
sst.end_time >= TIME('now');


0|0|0|SCAN TABLE sch AS sst (~185 rows)
0|0|0|EXECUTE LIST SUBQUERY 1

现在,如果我按顺序添加订单,那么他的查询计划会两次点击主表,并且比之前的表格长4倍,而表格有130万行,但过滤的行只有两行。

以下是新的查询计划:

sqlite3> EXPLAIN QUERY PLAN SELECT sst.prefix, 0 AS pb, sst.rate, 
sst.rate_n, sst.interval_1, sst.interval_n
FROM sch AS sst
WHERE
sst.i_workbook_id = 989 AND 
sst.prefix IN ('', '1', '19', '191', '1919', '19198') AND 
sst.activation_date <= DATETIME('now') AND 
(sst.expiration_date > DATETIME('now') OR sst.expiration_date IS NULL) AND
sst.start_time <= TIME('now') AND 
sst.end_time >= TIME('now') order by sst.prefix;     

0|0|0|EXECUTE LIST SUBQUERY 1
0|0|0|SEARCH TABLE sch AS sst USING AUTOMATIC COVERING INDEX (i_workbook_id=?) (~7 rows)
0|0|0|EXECUTE LIST SUBQUERY 1
0|0|0|SEARCH TABLE sch AS sst USING AUTOMATIC COVERING INDEX (i_workbook_id=?) (~7 rows)
0|0|0|EXECUTE LIST SUBQUERY 1
0|0|0|USE TEMP B-TREE FOR ORDER BY

有什么想法吗?我做错了什么?

1 个答案:

答案 0 :(得分:2)

SQLite尝试通过在i_workbook_id列上创建临时索引来优化您的第二个查询。 该查找已多次执行,因为OR表达式无法以更好的方式进行优化。 (请参阅query optimizerquery planner文档。)

你可以尝试做的是

  • i_workbook_id列上创建索引;或
  • i_workbook_idprefix列上创建索引;或
  • 在这两个上创建覆盖索引,然后在SELECTWHERE子句中提及所有其他列。