【发布时间】:2012-12-13 10:43:43
【问题描述】:
- 查询执行时间过长,大约需要 130 分钟。
- 具有索引但查询未使用索引的表。
- 表大小约为 3000 万条记录。
- 请帮助我通过更改(或)、(和)条件来重写查询。
- 查询未在正常执行中使用,因此我们尝试使用强制索引但没有成功。
查询:
SELECT customer_history.customer_id,
customer_history.row_mod,
customer_history.row_create,
customer_history.event_id,
customer_history.event_type,
customer_history.new_value,
customer_history.old_value
FROM customer_history FORCE INDEX (customer_history_n2)
WHERE customer_id >= 1
AND customer_id < 5000000
AND (customer_history.row_mod >= '2012-10-01')
OR (
customer_history.row_create >= '2012-10-01'
AND customer_history.row_create < '2012-10-13'
);
Table structure
CREATE TABLE `customer_history` (
`customer_id` int(11) NOT NULL,
`row_mod` datetime DEFAULT NULL,
`row_create` datetime DEFAULT NULL,
`event_id` int(11) DEFAULT NULL,
`event_type` varchar(45) DEFAULT NULL,
`new_value` varchar(255) DEFAULT NULL,
`old_value` varchar(255) DEFAULT NULL,
KEY `customer_id1` (`customer_id`),
KEY `new_value_n1` (`new_value`),
KEY `customer_history_n1` (`row_create`),
KEY `customer_history_n2` (`row_mod`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
解释计划:
+----+-------------+------------------+------+---------------------+------+---------+------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------------+------+---------------------+------+---------+------+----------+-------------+
| 1 | SIMPLE | customer_history | ALL | customer_history_n2 | NULL | NULL | NULL | 18490530 | Using where |
+----+-------------+------------------+------+---------------------+------+---------+------+----------+-------------+
1 row in set (0
【问题讨论】:
-
您必须将您的键组合成一个多列索引,以便为此类查询利用适当的索引
-
如果在查询前面加上 EXPLAIN 会得到什么?您是否绝对肯定确定这是您正在运行的查询,并且您不会为了方便而遗漏任何 JOIN 语句?另外,为什么要使用 FORCE INDEX 选项?
-
您可以为该表运行
SHOW TABLE STATUS和SHOW INDEXES吗?索引选择取决于基数,可能是在该表上运行OPTIMIZE的简单案例 -
发生了什么?你为什么取消我的答案是正确的?您是否找到了与解决您的问题的 FORCE INDEX 问题无关的其他内容?
-
对不起,你的答案是正确的。当我使用力指数时。它工作正常。
标签: mysql query-performance sql-execution-plan