此查询选择特定日期范围内的所有唯一访问者会话:
select distinct(accessid) from accesslog where date > '2009-09-01'
我在以下字段上有索引:
- 访问ID
- 日期
- 其他一些领域
这是解释的样子:
mysql> explain select distinct(accessid) from accesslog where date > '2009-09-01';
+----+-------------+-----------+-------+----------------------+------+---------+------+-------+------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-----------+-------+----------------------+------+---------+------+-------+------------------------------+
| 1 | SIMPLE | accesslog | range | date,dateurl,dateaff | date | 3 | NULL | 64623 | Using where; Using temporary |
+----+-------------+-----------+-------+----------------------+------+---------+------+-------+------------------------------+
mysql> explain select distinct(accessid) from accesslog;
+----+-------------+-----------+-------+---------------+----------+---------+------+---------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-----------+-------+---------------+----------+---------+------+---------+-------------+
| 1 | SIMPLE | accesslog | index | NULL | accessid | 257 | NULL | 1460253 | Using index |
+----+-------------+-----------+-------+---------------+----------+---------+------+---------+-------------+
为什么带有 date 子句的查询不使用 accessid 索引?
是否有任何其他索引可以用来加快在某些日期范围内对不同 accessid 的查询?
编辑 - 分辨率
将列宽accessid
从 varchar 255 减少到 char 32 将查询时间缩短了约 75%。
添加date+accessid
索引对查询时间没有影响。