我有包含三个表的 sqlite3 数据库:
CREATE TABLE document (
id Int PRIMARY KEY NOT NULL,
root_id Int,
name Varchar(100),
active Tinyint
);
CREATE INDEX IDX_documentId ON document (id);
CREATE INDEX IDX_documentName ON document (name);
CREATE TABLE dictionary (
id Int PRIMARY KEY NOT NULL,
word Varchar(100) NOT NULL
);
CREATE INDEX IDX_dictionaryId ON dictionary (id);
CREATE UNIQUE INDEX IDX_dictionaryWord ON dictionary (word ASC);
CREATE TABLE document_index (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
document_id Int NOT NULL,
word_id Int NOT NULL,
FOREIGN KEY(document_id) REFERENCES document(id),
FOREIGN KEY(word_id) REFERENCES dictionary(id)
);
CREATE INDEX IDX_documentIndexId ON document_index (id);
CREATE INDEX IDX_documentIndexDocId ON document_index (document_id);
CREATE INDEX IDX_documentIndexWordId ON document_index (word_id);
我有 sql 脚本来选择包含字典中单词的所有文档:
SELECT document.id, document.name
FROM document
INNER JOIN document_index on document_index.document_id=document.id
INNER JOIN dictionary on dictionary.id=document_index.word_id
WHERE dictionary.word LIKE @pQuery
AND document.active = 1
AND document.root_id in (@pRoot1, @pRoot2, @pRoot3, @pRoot4, @pRoot5, @pRoot6, @pRoot7)
当字典包含 ~= 400,000 条记录、document ~= 1000 条记录和 document_index ~= 500,000 条记录时,查询在我的 iPad 2 上执行大约 30 秒。
如何优化查询或改变数据库结构(例如添加索引)以减少查询时间?