我正在尝试优化 SQL 查询。问题是它非常慢!我正在使用 sqlite 和中型数据集(20000row)。我的 sql 语法如下所示:
SELECT DISTINCT date(A.last_update) as lastUpdate,
(SELECT COUNT(*) FROM bgp_update AS B WHERE date(B.last_update) = date(A.last_update) AND B.validity = 1) AS valid,
(SELECT COUNT(*) FROM bgp_update AS B WHERE date(B.last_update) = date(A.last_update) AND B.validity = 0) AS invalid,
(SELECT COUNT(*) FROM bgp_update AS B WHERE date(B.last_update) = date(A.last_update) AND B.validity = -1) AS notFound
FROM (SELECT DISTINCT last_update FROM bgp_update ORDER BY last_update) AS A WHERE last_update BETWEEN '%var' and '%var2';
以下是我拥有的示例:
id | last_update | Validity
48 | 2009-1-6 18:34:38 | notFound
47 | 2009-1-6 18:34:38 | valid
46 | 2009-1-6 18:34:38 | valid
45 | 2009-1-3 18:34:38 | invalid
44 | 2009-1-3 18:34:38 | invalid
42 | 2009-1-4 18:34:38 | notFound
41 | 2009-1-4 18:34:38 | notFound
48 | 2009-1-4 18:34:38 | valid
查询结果如下所示:
Date | valid | invalid | notFound
2009-1-3 | 0 | 2 | 0
2009-1-4 | 1 | 0 | 2
2009-1-6 | 2 | 0 | 1
我需要这个来生成一个折线图。例如:折线图!
但正如我提到的,查询非常慢!我怎样才能让它更快?
:::: 2. 编辑 :::::
前面的描述我已经简化了问题。我的表创建语句如下所示:
CREATE TABLE bgp_update
(id INTEGER PRIMARY KEY,
ip VARCHAR(64) NOT NULL,
mask INTEGER NOT NULL,
asn INTEGER NOT NULL,
validity INTEGER NOT NULL,
last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
如您所见,我的查询仅使用 last_update 和有效性字段。