简体   繁体   English

MySQL拒绝使用索引进行简单查询

[英]MySQL Refusing to Use Index for Simple Query

I have a table that I'm running a very simple query against. 我有一个要对其运行非常简单查询的表。 I've added an index to the table on a high cardinality column, so MySQL should be able to narrow the result almost instantly, but it's doing a full table scan every time. 我在基数高的列上的表中添加了索引,因此MySQL应该能够几乎立即缩小结果范围,但是每次都在进行全表扫描。 Why isn't MySQL using my index? 为什么MySQL不使用我的索引?

mysql> select count(*) FROM eventHistory;
+----------+
| count(*) |
+----------+
|   247514 |
+----------+
1 row in set (0.15 sec)

CREATE TABLE `eventHistory` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    `whatID` varchar(255) DEFAULT NULL,
    `whatType` varchar(255) DEFAULT NULL,
    `whoID` varchar(255) DEFAULT NULL,
    `createTimestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    KEY `whoID` (`whoID`,`whatID`)
) ENGINE=InnoDB;

mysql> explain SELECT * FROM eventHistory where whoID = 12551\G
*************************** 1. row ***************************
            id: 1
   select_type: SIMPLE
         table: eventHistory
         type: ALL
possible_keys: whoID
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 254481
        Extra: Using where
1 row in set (0.00 sec)

I have tried adding FORCE INDEX to the query as well, and it still seems to be doing a full table scan. 我也尝试将FORCE INDEX添加到查询中,它似乎仍在进行全表扫描。 The performance of the query is also poor. 查询的性能也很差。 It's currently taking about 0.65 seconds to find the appropriate row. 当前需要大约0.65秒才能找到合适的行。

The above answers lead me to realize two things. 上面的答案使我意识到两件事。

1) When using a VARCHAR index, the query criteria needs to be quoted or MySQL will refuse to use the index (implicitly casting behind the scenes?) 1)当使用VARCHAR索引时,查询条件需要加引号,否则MySQL将拒绝使用该索引(隐式在幕后进行转换?)

SELECT * FROM foo WHERE column = '123'; # do this
SELECT * FROM foo where column = 123; # don't do this

2) You're better off using/indexing an INT if at all possible. 2)如果可能的话,最好使用/索引INT。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM