【问题标题】:How to determine what to Index in a MySQL Table如何确定 MySQL 表中要索引的内容
【发布时间】:2014-02-09 04:34:20
【问题描述】:

我有以下疑问:

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 秒(慢!)。我相信我可以使用索引来加快速度,因为下面的查询需要

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       

有人可以向我解释索引是否会加快我的顶级查询,如果可以,我如何确定我需要索引什么?

谢谢!

【问题讨论】:

    标签: mysql performance indexing


    【解决方案1】:

    您想要索引您正在过滤的字段。即 WHERE 字段。把它想象成一本书。 “WHERE”字段是您在书中寻找的内容。没有索引,你就没有目录,所以当你想查找信息时,你必须搜索每一页,每一个词。如果你有一个索引,在你的书中这个例子,你可以查看目录并发现第 X 章有你的信息,所以转到那一章,你可以更快地找到你的数据。

    【讨论】:

    • 谢谢!但是,如果您检查我发布的上述两个查询,它们与我选择的内容相同(换句话说,WHERE 子句是相同的)。第一个查询非常慢,但第二个查询(我选择 MAC 的位置)在 MS 时间范围内。这让我觉得还有其他事情发生。
    猜你喜欢
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 2012-07-07
    相关资源
    最近更新 更多