mysql适当的索引为where和group

时间:2013-04-03 03:49:44

标签: mysql indexing group-by where

我有这样的表

tbl_reg_process
- id, bigint(20)
- x1, varchar(255) nullable
- x2, varchar(255) nullable
- x3, varchar(255) nullable
- date1, datetime, nullable

这是解释查询:

EXPLAIN SELECT x1,COUNT(x1) FROM tbl_reg_process WHERE date1 >= '2013-04-01 00:00:00' AND x3='U' GROUP BY x1

这是结果( INDEX NOT USED ),我的反应非常缓慢

+----+-------------+-----------------+------+---------------+--------+---------+-------+--------+----------------------------------------------+
| id | select_type | table           | type | possible_keys | key    | key_len | ref   | rows   | Extra                                        |
+----+-------------+-----------------+------+---------------+--------+---------+-------+--------+----------------------------------------------+
|  1 | SIMPLE      | tbl_reg_process | ref  | x3,date1      | status | 768     | const | 585521 | Using where; Using temporary; Using filesort |
+----+-------------+-----------------+------+---------------+--------+---------+-------+--------+----------------------------------------------+

问题是,我应该创建什么索引,以便我可以使用包含date1,x3和x1的条件?

1 个答案:

答案 0 :(得分:1)

如果x1x3完全匹配,且date1通常不平等,则索引应位于(x1, x3, date1)(x3, x1, date1)上。一般的想法是WHERE子句中的不等式应该使用索引中的最后一列。