IN clause not using index

后端 未结 2 1918
无人共我
无人共我 2021-01-22 06:00

Here is the table definition

CREATE TABLE `dt_prdtime` (
  `TCompany` varchar(3) NOT NULL DEFAULT \'\',
  `TPerCode` varchar(8) NOT NULL,
  `TBegDateTime` dateti         


        
相关标签:
2条回答
  • 2021-01-22 06:01

    Neither MyISAM, nor InnoDB, is likely to use an index when "too much" of the table needs to be fetched.

    IN (5,6) may mean 2/12ths of the table needs to be scanned? Or maybe the data is biased such that those two months have more than their share of rows?

    The reason the optimizer might eschew the index in cases like this...

    When using such an index, it needs to spend a lot of time bouncing between the index (one BTree) and the data.

    When not using the index, it simply cruises through the data, ignoring 10/12ths of the rows. This may actually be faster.

    0 讨论(0)
  • 2021-01-22 06:04

    I will go out on a limb and say it is because you are using the MyISAM engine.

    It is working perfectly fine with INNODB as can be seen in this Answer of mine.

    I will try to spook up at least 1 honorable reference on the matter.

    Here, The range Join Type, clearly an INNODB focus as it is the default engine. And when not explicitly mentioned in the manual in some documentation hierarchy, it is assumed.

    Note, there is nothing contiguous about the id's in my example link. Meaning, don't hyperfocus on type=range in its EXPLAIN output. The speed is arrived at via the Optimizer (the CBO).

    The cardinality in my example is very high (4.3 Million). The target id counts are relatively low (1000). The index is used.

    Your situation may be the opposite: your cardinality might be incredibly low, like 3, and the optimizer decides to abandon use of the index.

    To check your index cardinality, see the Manual Page SHOW INDEX Syntax.

    A simple call such as:

    show index from ratings;
    
    +---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    | Table   | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
    +---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    | ratings |          0 | PRIMARY  |            1 | id          | A         |     4313544 |     NULL | NULL   |      | BTREE      |         |               |
    +---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
    
    0 讨论(0)
提交回复
热议问题