可以使用哪些索引来改进此查询?

Ian*_*Ian 0 mysql indexing optimization distinct

此查询选择特定日期范围内的所有唯一访问者会话:

select distinct(accessid) from accesslog where date > '2009-09-01'
Run Code Online (Sandbox Code Playgroud)

我有以下字段的索引:

  • ACCESSID
  • 日期
  • 其他一些领域

这是解释的样子:

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 |
+----+-------------+-----------+-------+---------------+----------+---------+------+---------+-------------+
Run Code Online (Sandbox Code Playgroud)

为什么带有date子句的查询不使用accessid索引?

在某些日期跨度中,是否还有其他可用于加速查询不同accessid的索引?

编辑 - 解决方案

将列宽accessid从varchar 255 减少到char 32,将查询时间缩短了约75%.

添加date+accessid索引对查询时间没有影响.

Jos*_*vis 5

索引(date,accessid) 可能有所帮助.但是,在调整索引之前,我建议您检查accessid列的类型.EXPLAIN说密钥长257个字节,对于ID列来说听起来很多.你用的是VARCHAR(256)for accessid?如果是这样,你不能使用更紧凑的类型吗?如果它是一个数字,它应该是INT(SMALLINT,BIGINT不管你需要什么),如果它是一个字母数字ID,它真的可以是256个字符长吗?如果它的长度是固定的,你不能使用CHAR(CHAR(32)例如)吗?