选择的mysql时间与实际行不同

标签 mysql select explain

我在我的 mysql 服务器中遇到了意外结果。

行数越多,查询时间越少??

我有一个表,每个过滤器的总行数:

select count(*) from tcr where eid=648;
+----------+
| count(*) |
+----------+
|    11336 |
select count(*) from tcr  where eid=997;
+----------+
| count(*) |
+----------+
|  1262307 |

但查询时间与每个过滤器的总行数相反:

select * from tcr where eid=648 order by start_time desc limit 0,10;
[data display]
10 rows in set (16.92 sec)

select * from tcr  where eid=997 order by start_time desc limit 0,10;
[data display]
10 rows in set (0.21 sec)

“reset query cache”在每条查询sql之前都执行过。 表 tcr 的索引是

KEY `cridx_eid` (`eid`),
KEY `cridx_start_time` (`start_time`)

顺便说一句:附上解释结果:这很奇怪,但它看起来更像我们得到的结果。(eid=997 的行数比 eid=648 少

explain select * from talk_call_record where eid=648 order by start_time desc limit 0,10;
+----+-------------+------------------+-------+---------------+------------------+---------+------+------+-------------+

|编号 |选择类型 |表 |类型 |可能的键 | key | key 长度 |引用 |行 |额外 | +----+------------+----------------+--------+-- ----------+----------------+--------+------+- -----+--------------+ | 1 |简单 | talk_call_record | 通话记录索引 | cridx_eid | cridx_start_time | 5 |空 | 3672 |使用哪里 |

explain select * from talk_call_record where eid=997 order by start_time desc limit 0,10;
+----+-------------+------------------+-------+---------------+------------------+---------+------+------+-------------+

| id | select_type | table            | type  | possible_keys | key              | key_len | ref  | rows | Extra       |
+----+-------------+------------------+-------+---------------+------------------+---------+------+------+-------------+
|  1 | SIMPLE      | talk_call_record | index | cridx_eid     | cridx_start_time | 5       | NULL |   32 | Using where |

最佳答案

首先,你必须有一张非常大的 table 。

MySQL 正在使用 start_time 上的索引进行查询。正在发生的事情是它正在“走”过表格,一次一行。它碰巧找到 eid=997 比找到 eid=648 快得多。它只需要找到 10 条记录,所以引擎在找到第 10 条时停止。

你能做什么?查询的最佳索引是 (eid, start_time) 上的复合索引。这将直接转到您想要的值。

关于选择的mysql时间与实际行不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42761576/

相关文章:

mysql - 如何获得 MySQL "Explain"的虚拟值?

php - 将 json 传递给 php 并更新 mysql

mysql - 从多个表中选择数据 - laravel

mysql - 如何使用多个连接和子查询优化这个慢速查询

mysql - 如何在 SQL 中使用集合代数运算

mysql SELECT 超过 1 个或

postgresql - 缓慢的 Postgres 9.3 查询,再次

java - 如何修复 BoneCP 中的 : Exception in thread "main" java. lang.NoClassDefFoundError

mysql - 更改 phpmyadmin 中的默认字段

mysql - 当输入值为 NULL 时,多个 CASE 语句不起作用