首页 > 解决方案 > 防止 SQLite 查询执行 USE TEMP B-TREE FOR GROUP BY

问题描述

我有一张桌子

CREATE TABLE user_records (
pos smallint PRIMARY KEY, 
username MEDIUMINT unsigned not null,
anime_id smallint UNSIGNED NOT NULL,  
score tinyint not null,
scaled_score DECIMAL(1,5) not null
)

带索引

(anime_id,username,scaled_score)
(username,anime_id,scaled_score)
(username)
(anime_id) 

我知道最后两个是多余的,我只是在测试

最后是我的查询:

select aggregate_func(score2) scores,anime_id from 
(select anime_id as anime_id2,username as username2,scaled_score as score2  from user_records where anime_id in(666)) 
inner join  
(select anime_id,username,scaled_score from user_records)
where  username = username2  group by anime_id  order by scores desc limit 1000;

此查询的目标是对用户对指定节目(在本例中为 666)和表中所有其他节目的评分的每个组合运行聚合函数。我已经尝试了 SQLite 支持的每种类型的连接,但并不多,并重新排序了 select 语句,但结果总是相同的,除了首先使用无约束选择的交叉连接,这需要很长时间,原因很明显。在单独执行每个部分后,我确信花费最多时间的部分是 USE TEMP B-TREE FOR GROUP BY。我的目标是让查询规划器以某种方式使用 GROUP BY 的索引,但无论我尝试什么,它都会选择 B-TREE,并且根据连接结果集的大小,分组过程所需的时间呈指数增长。

作为参考,该表有 70,000,000 行用户节目评分,并且 GROUP by 通常必须处理数百万个连接行。提前致谢。

标签: sqlsqlite

解决方案


推荐阅读