SQL查询 - 需要改进

时间:2014-02-24 23:19:14

标签: sql sqlite

我有一个类似下面的SQL语句,我在tableA中只有大约20000条记录,在tableB中只有1000条,但查询大约需要5秒,有没有简单的方法可以提高查询速度,谢谢!! (请注意,UNION可能有两个以上的表)

我认为性能瓶颈不是来自'UNION',如果我只是从tableA查询,时间几乎相同,任何想法?

SELECT * 
FROM (SELECT * FROM tableA 
      UNION ALL 
      SELECT * FROM tableB) AS table 
 WHERE id >= 1
 AND deleted = '0' 
 ORDER BY time DESC, id DESC 
 LIMIT 100;

2 个答案:

答案 0 :(得分:3)

一种方法是删除子查询并将条件移近表格:

(SELECT *
 FROM tableA
 WHERE id >= 1 AND deleted = '0'
) UNION ALL
(SELECT *
 FROM tableB
 WHERE id >= 1 AND deleted = '0'
) 
ORDER BY time DESC, id DESC
LIMIT 100;

然后创建两个索引:

create index tableA_deleted_id on tableA(deleted, id);
create index tableB_deleted_id on tableB(deleted, id);

答案 1 :(得分:0)

查看执行计划,看看发生了什么。如果你看一下this fiddle,你会看到它的评估方式存在显着差异。

在索引之前:

SEARCH TABLE tableA USING INTEGER PRIMARY KEY (rowid>?) (~25000 rows)
USE TEMP B-TREE FOR ORDER BY
SEARCH TABLE tableB USING INTEGER PRIMARY KEY (rowid>?) (~25000 rows)
USE TEMP B-TREE FOR ORDER BY
COMPOUND SUBQUERIES 1 AND 2 (UNION ALL)

索引之后:

SEARCH TABLE tableA USING INDEX IX_tableA (deleted=?) (~3 rows)
USE TEMP B-TREE FOR ORDER BY
SEARCH TABLE tableB USING INDEX IX_tableB (deleted=?) (~3 rows)
USE TEMP B-TREE FOR ORDER BY
COMPOUND SUBQUERIES 1 AND 2 (UNION ALL)