我在SQLite数据库中有一个表TABLE,其中包含DATE,GROUP列。我想选择每组中的前10个条目。在stackoverflow上研究类似主题后,我提出了以下查询,但运行速度非常慢。任何想法如何让它更快?
select * from TABLE as A
where (select count(*) from TABLE as B
where B.DATE < A.DATE and A.GROUP == B.GROUP) < 10
这是EXPLAIN QUERY PLAN(TABLE = clients_bets)的结果:
答案 0 :(得分:2)
以下是一些建议:
使用覆盖索引(包含子查询中所需数据的索引,在本例中为组和日期)
create index some_index on some_table(some_group, some_date)
此外,重写要查询的子查询较少依赖于外部查询:
select * from some_table as A
where rowid in (
select B.rowid
from some_table as B
where A.some_group == B.some_group
order by B.some_date limit 10 )
查询计划更改为:
0 0 0 SCAN TABLE some_table AS A
0 0 0 EXECUTE CORRELATED LIST SUBQUERY 1
1 0 0 SEARCH TABLE some_table AS B USING COVERING INDEX idx_1 (some_group=?)
到
0 0 0 SCAN TABLE some_table AS A
0 0 0 EXECUTE CORRELATED SCALAR SUBQUERY 1
1 0 0 SEARCH TABLE some_table AS B USING COVERING INDEX idx_1 (some_group=? AND some_date<?)
虽然它非常相似,但查询看起来要快得多。我不确定原因。