在 SQLite 3.20.1 中,我创建了一个 R*Tree 索引 ( dog_bounds
) 和一个临时表 ( frisbees
),如下所示:
-- Changes infrequently and has ~100k entries
CREATE VIRTUAL TABLE dog_bounds USING rtree (
dog_id,
min_x, max_x,
min_y, max_y
);
-- Changes frequently and has ~100 entries
CREATE TEMPORARY TABLE frisbees (
frisbee_id,
min_x, max_x,
min_y, max_y
);
使用此索引进行查询很快,如下所示:
EXPLAIN QUERY PLAN
SELECT dog_id FROM dog_bounds AS db, frisbees AS f
WHERE db.max_x >= f.min_x AND db.max_y >= f.min_y
AND db.min_x < f.max_x AND db.min_y < f.max_y;
0|0|1|SCAN TABLE frisbees AS f
0|1|0|SCAN TABLE dog_bounds AS db VIRTUAL TABLE INDEX 2:D1D3C0C2
但是,如果我 select DISTINCT(dog_id)
,则不再使用索引,并且查询会变慢,即使在以下情况下也是如此ANALYZE
:
EXPLAIN QUERY PLAN
SELECT DISTINCT(dog_id) FROM dog_bounds AS db, frisbees AS f
WHERE db.max_x >= f.min_x AND db.max_y >= f.min_y
AND db.min_x < f.max_x AND db.min_y < f.max_y;
0|0|0|SCAN TABLE dog_bounds AS db VIRTUAL TABLE INDEX 2:
0|1|1|SCAN TABLE frisbees AS f
0|0|0|USE TEMP B-TREE FOR DISTINCT
我怎样才能获得这里使用的 R*Tree 索引?复制狗将是一种耻辱!