如何加快这个MySQL查询?

时间:2012-07-05 05:32:09

标签: mysql sql query-optimization

mysql> EXPLAIN SELECT col1, col2 FROM t WHERE col1 REGEXP '^foobar_[0-9]{4}$';
+----+-------------+---------------+------+---------------+------+---------+------+--------+-------------+
| id | select_type | table         | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
+----+-------------+---------------+------+---------------+------+---------+------+--------+-------------+
|  1 | SIMPLE      |        t      | ALL  | NULL          | NULL | NULL    | NULL | 757000 | Using where | 
+----+-------------+---------------+------+---------------+------+---------+------+--------+-------------+
1 row in set (0.15 sec)

mysql> DESCRIBE t;
+------------------------+------------------------+------+-----+---------+-------+
| Field                  | Type                   | Null | Key | Default | Extra |
+------------------------+------------------------+------+-----+---------+-------+
| col2                   | varchar(255)           | NO   | MUL | {}      |       | 
| col1                   | varbinary(255)         | NO   | PRI |         |       | 
+------------------------+------------------------+------+-----+---------+-------+
2 rows in set (0.22 sec)

2 个答案:

答案 0 :(得分:2)

如果您对col1有索引,请添加LIKE,如下所示:

SELECT col1, col2
FROM t 
WHERE col1 LIKE 'foobar_%' AND col1 REGEXP '^foobar_[0-9]{4}$';

你应该提高速度。

你也可以创建一个索引(col1,col2),使mysql在memeory中存储该表的副本

答案 1 :(得分:0)

您可以通过创建第三行来加速此查询,如果它始终相同,则您已经预先计算了RegEx。

MySQL似乎不支持function based indexes