我有以下查询:

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/

10-11 20:20
查看更多