mysql - 如何确定在 MySQL 表中索引的内容

标签 mysql performance indexing

我有以下查询:

SELECT TIMESTAMPDIFF(MINUTE, firstOccurrence, lastOccurrence) as dwellTime
FROM ts_VisitorDuration
WHERE eventDate >= '2012-12-01'
AND eventDate <= '2014-03-03'
AND venueID = 1007
GROUP BY MACAddress, eventDate

运行需要 12 到 17 秒(慢!)。我相信我可以使用索引来加快速度,因为下面的查询运行时间不到 1 秒 - 在 WHERE 子句中使用相同的表和条件:

SELECT MACAddress
FROM ts_VisitorDuration
WHERE eventDate >= '2012-12-01'
AND eventDate <= '2014-03-03'
AND venueID = 1007
GROUP BY MACAddress, eventDate

我尝试对我认为正确的列进行索引,但它似乎并没有影响性能。

这是顶部(慢速)查询的EXPLAIN:

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  ts_VisitorDuration  range   PRIMARY,venueID venueID 7   NULL    167776  Using where; Using temporary; Using file sort

并在表上使用 SHOW INDEX FROM 给出:

Table   Non_unique  Key_name    Seq_in_index    Column_name Collation   

Cardinality Sub_part    Packed  Null    Index_type  Comment Index_comment
ts_VisitorDuration  0   PRIMARY 1   eventDate   A   21  NULL    NULL        BTREE       
ts_VisitorDuration  0   PRIMARY 2   MACAddress  A   11714214    NULL    NULL        BTREE       
ts_VisitorDuration  0   PRIMARY 3   venueID A   11714214    NULL    NULL        BTREE       
ts_VisitorDuration  1   venueID 1   venueID A   4542    NULL    NULL        BTREE       
ts_VisitorDuration  1   venueID 2   eventDate   A   172267  NULL    NULL        BTREE       
ts_VisitorDuration  1   MACAddress  1   MACAddress  A   11714214    NULL    NULL        BTREE       
ts_VisitorDuration  1   MACAddress  2   eventDate   A   11714214    NULL    NULL        BTREE       
ts_VisitorDuration  1   MACAddress  3   venueID A   11714214    NULL    NULL        BTREE       
ts_VisitorDuration  1   MACAddress  4   firstOccurrence A   11714214    NULL    NULL        BTREE       
ts_VisitorDuration  1   MACAddress  5   lastOccurrence  A   11714214    NULL    NULL    YES BTREE       
ts_VisitorDuration  1   firstOccurrence 1   firstOccurrence A   11714214    NULL    NULL        BTREE       

有人可以向我解释一下索引是否会加速我的热门查询,如果是的话,我如何确定需要索引的内容?

谢谢!

最佳答案

您想要对正在过滤的字段建立索引。即 WHERE 字段。把它想象成一本书。 “WHERE”字段是您在书中查找的内容。没有索引,就没有目录,因此当您想要查找信息时,您必须搜索每个页面、每个单词。如果您在本示例的书中有索引,则可以查看目录并发现第 X 章包含您的信息,因此转到该章,您会更快地找到数据。

关于mysql - 如何确定在 MySQL 表中索引的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21655331/

相关文章:

java - 慢速双缓冲方法

MySQL 使用索引更新查询速度极慢

indexing - 阻止某些地址被抓取 Robots.txt

php - 为什么 JSON 只为我的查询返回 1 个图像输出?

performance - 提高 4G 网络数据速率的各种选项有哪些?

php - mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows 等...期望参数 1 是资源

Java引入临时对象

postgresql - Postgres Gin 索引读取性能

php - 为什么我的查询只获取 3 个项目而不是预期的数量?

PHP 日期转换(带斜杠)