Search code examples
mysqlselectexplain

mysql time for select not same as real lines


I met a unexpect result in my mysql server.

the lines more , the query time less??

I have one table and for the total rows for each filter:

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

but the query time is oppisite to the total lines for each filter:

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" has been execute before every query sql. the index of table tcr is

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

BTW:attach the explain result: this is very strange, but it looks more like the reuslt we take.(the eid=997 has less lines than eid=648

explain select * from talk_call_record where eid=648 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 | 3672 | Using where |

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 |

Solution

  • First, you must have a very large table.

    MySQL is using the index on start_time for the queries. What is happening is that it is "walking" through the table, one row at a time. It happens to find eid=997 much more quickly than it finds eid=648. It only has to find 10 records, so the engine stops when it gets to the 10th one.

    What can you do? The optimal index for the query is a composite index on (eid, start_time). This will go directly to the values that you want.