我已尝试过此查询的不同变体,但我无法使用时间戳索引。我做错了什么?
任何帮助将不胜感激:)
MariaDB [alienvault]> explain extended SELECT * FROM alienvault_siem.acid_event WHERE (timestamp BETWEEN '2012-10-09 11:20:17' AND '2012-10-10 03:20:17');
+------+-------------+------------+------+---------------+------+---------+------+---------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+------+-------------+------------+------+---------------+------+---------+------+---------+----------+-------------+
| 1 | SIMPLE | acid_event | ALL | timestamp | NULL | NULL | NULL | 4481579 | 50.00 | Using where |
+------+-------------+------------+------+---------------+------+---------+------+---------+----------+-------------+
1 row in set, 1 warning (0.01 sec)
表格结构:
CREATE TABLE IF NOT EXISTS `acid_event` (
(...)
`timestamp` datetime NOT NULL,
(...)
PRIMARY KEY (`id`),
(...)
KEY `timestamp` (`timestamp`),
(...)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
软件:Percona Server
软件版本:5.5.27-28.1 - Percona Server(GPL),版本28.1
答案 0 :(得分:3)
可能由以下原因引起: - 索引没有足够的选择性,mysql认为全扫描会更快 - mysql的索引统计信息不好
您可以检查“SHOW INDEX FROM alienvault_siem.acid_event;”的输出 您也可以尝试强制使用索引(但如果fullscan更快,则可能会很糟糕):
SELECT * FROM alienvault_siem.acid_event FORCE INDEX (`timestamp`) WHERE (timestamp BETWEEN '2012-10-09 11:20:17' AND '2012-10-10 03:20:17');
答案 1 :(得分:1)
问题在于您将日期文字提供为字符串。
如果您使用
中的str_to_date()
功能
WHERE timestamp
BETWEEN str_to_date('2012-10-09 11:20:17','%Y-%m-%d %H:%i:%s')
AND str_to_date('2012-10-10 03:20:17','%Y-%m-%d %H:%i:%s')
然后MySQL将能够使用索引。