我需要一些帮助来优化以下查询:
SELECT
kd2c.id as _id,
kd2c.literal as kanji
FROM
kd2_character as kd2c
JOIN krad_components as kcom ON kcom.kanji_fk = kd2c.id
WHERE kcom.radical_fk IN (1, 2, 3, etc...)
GROUP BY kd2c.id HAVING count(distinct kcom.radical_fk) = <number of integers in WHERE clause>
ORDER BY kd2c.freq IS NULL ASC, kd2c.freq, kd2c.id
查询本身(无论WHERE
子句中的 fk 数量如何)需要 0.04 秒才能运行,相对于我所有其他需要大约 0.0003 秒的查询来说,这是一个很长的时间。我EXPLAIN QUERY PLAN
反对上述声明并收到以下内容:
# | selectid | order | from | detail
1 0 0 0 SCAN TABLE kd2_character AS kd2c USING INTEGER PRIMARY KEY (~1000000 rows)
2 0 1 1 SEARCH TABLE krad_components AS kcom USING COVERING INDEX idx_krad_components (kanji_fk=? AND radical_fk=?) (~9 rows)
3 0 0 0 EXECUTE LIST SUBQUERY 1
4 0 0 0 USE TEMP B-TREE FOR ORDER BY
我很确定脚本需要很长时间,因为最初的SCAN TABLE
. 如果是这样,我该如何摆脱它?我认为创建索引kd2_characer.id
会有所帮助,但它对执行时间没有任何明显影响。
如何改进此查询?有没有更好的方法来构建 my GROUP BY
,因为它可能是SCAN
?