Home > Database > Mysql Tutorial > 由浅入深讲解MySQL数据库索引的选择性_MySQL

由浅入深讲解MySQL数据库索引的选择性_MySQL

WBOY
Release: 2016-06-01 14:00:55
Original
972 people have browsed it

在MySQL中,对于索引的使用并是一直都采用正确的决定。

  简单表的示例:

  create TABLE `r2` (
  ID` int(11) DEFAULT NULL,
  ID1` int(11) DEFAULT NULL,
  CNAME` varchar(32) DEFAULT NULL,
  KEY `ID1` (`ID1`)
  ) ENGINE=MyISAM DEFAULT charSET=latin1
  select count(*) FROM r2;
  250001 (V1)
  select count(*) FROM r2 where ID1=1;
  83036 (V2)
  (execution time = 110 ms)

  (ID1=1)条件查询索引的选择性是 V2/V1 = 0.3321 或 33.21%

  一般来说(例如书 “SQL Tuning“),如果选择性超过 20% 那么全表扫描比使用索引性能更优。

  我知道Oracle一直是在选择性超过25%时会选择全表扫描。

  而MySQL呢:

  mysql> EXPLAIN select count(SUBNAME) FROM r2 where ID1=1;

  +----+-------------+-------+------+---------------+-----

  | id | select_type | TABLE | type | possible_keys | KEY | key_len | ref | rows | Extra |

  +----+-------------+-------+------+---------------+-----

  | 1 | SIMPLE | t2 | ref | ID1 | ID1 | 5 | const | 81371 | USING where |

  +----+-------------+-------+------+---------------+-----

  这就是MySQL将会使用索引来完成这个查询。

  让我们来对比索引查询和全表扫描的执行时间:

  select count(SUBNAME) FROM t2 where ID1=1 - 410 ms

  select count(SUBNAME) FROM t2 IGNORE INDEX (ID1) where ID1=1 - 200 ms

  如你所看到全表扫描要快2倍。

  参考更特殊的例子:选择性 ~95%:

  select cnt2 / cnt1 FROM (select count(*) cnt1 FROM r2) d1, (select count(*) cnt2 FROM r2 where ID1=1) d2;

  0.9492 = 94.92%;

  说明MySQL将会用索引来完成查询。

  执行时间:

  select count(SUBNAME) FROM t2 where ID1=1 - 1200 ms

  select count(SUBNAME) FROM t2 IGNORE INDEX (ID1) where ID1=1 - 260 ms

  这次全表扫描要快4.6倍。

  为什么MySQL选择索引访问查询?

  MySQL没有计算索引的选择性,只是预测逻辑IO操作的数量,并且我们的例子中间的逻辑IO数量,索引访问要少于全表扫描。

  最后我们得出结论,对于索引要小心使用,因为它们并不能帮助所有的查询

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template