mysql 解释中更高的行数意味着好还是坏?

Does higher rows count in mysql explain means good or bad?

我有一个旧的 MyISAM table,当我提交一些计数查询时,table 被锁定。如果我在同一个 InnoDB table 上执行相同的查询,查询将快速执行。问题是,旧的 MyISAM table 仍在生产中使用并且负载很重,而新的则不是。

现在我们来谈谈我的问题。当我解释在两个 table 中执行的查询时,我得到一些让我感到困惑的结果。

这是我在两个 table 中执行的查询:

SELECT COUNT(*)
FROM table
WHERE vrsta_dokumenta = 3
    AND dostupnost = 0

这是旧版 MyISAM table 的解释:

id select_type table     type possible_keys         key               key_len ref    rows   Extra    
1  SIMPLE     old_table  ref idx_vrsta_dokumenta idx_vrsta_dokumenta     1   const 564253  Using where 

这是来自新 InnoDB 的解释 table:

id select_type   table  type    possible_keys         key           key_len  ref    rows   Extra     
1  SIMPLE      new_table ref idx_vrsta_dokumenta idx_vrsta_dokumenta   1    const 611905 Using where

如您所见,新版 table 中的行数高于旧版。

所以如果数字越大越好,这是否意味着新 table 的查询在完全使用后会变慢?

如果数字越大越好,那么也许这就是为什么 new table 更快,而 MyISAM 在执行一段时间后被锁定的原因。

无论如何,什么是正确的?这个行数是什么意思?

编辑:旧 table 的列数是新列的两倍。由于旧 is 已拆分为 2 tables.

行计数告诉您 MySQL 必须检查多少行才能获得查询结果。这是索引提供帮助的地方,一个名为 index cardinality 的数字发挥着非常重要的作用。索引有助于 MySQL 减少检查行的次数,因此检查的次数越少 - 速度越快。由于有很多行满足 vrsta_dokumenta = 3 AND dostupnost = 0 的条件,因此 MySQL 只需遍历这些行,找到它们并递增计数器。对于 MyISAM,这意味着 MySQL 必须从磁盘读取数据——这很昂贵,因为磁盘访问速度非常慢。对于 InnoDB,它非常快,因为 InnoDB 可以将其工作数据集存储在内存中。换句话说,MyISAM 从磁盘读取,而 InnoDB 从内存读取。还有其他可用的优化,但一般规则是 InnoDB 将比 MyISAM 更快,即使有 table 增长。

黑屋小子:

So in the case that higher number is bad, does this mean that query on the new table will be slower once it is fully in use?

MySQL manual 说明 EXPLAIN:

中的行列

The rows column indicates the number of rows MySQL believes it must examine to execute the query.

For InnoDB tables, this number is an estimate, and may not always be exact.

所以,更高的数字还不错,这只是基于 table 元数据的猜测。

黑屋小子:

In case the higher number is good, then maybe that is the reason why new table is faster, and MyISAM gets locked after some time of execution.

数字越大越好。 MyISAM 被锁定不是因为这个数字。

Manual:

MySQL uses table-level locking for MyISAM, allowing only one session to update those tables at a time, making them more suitable for read-only, read-mostly, or single-user applications.

... Table updates are given higher priority than table retrievals... If you have many updates for a table, SELECT statements wait until there are no more updates.

如果您的 table 经常更新,它会被 INSERT、UPDATE 和 DELETE (a.k.a.DML) 语句锁定,这会阻止您的 SELECT 查询。