简体   繁体   English

为什么向用于连接两个表的两个键之一添加索引会使执行时间比根本不使用任何索引要慢?

[英]Why does adding an index to one of the two keys used to join two tables make the execution time slower than not using any index at all?

I am executing queries where two tables authors and work_authors are being joined.我正在执行查询,其中连接了两个表authorswork_authors I am using MySQL.我正在使用 MySQL。 authors and work_authors have a one-to-many relationship and authors contains around 7 million records and work_authors contains around 21 million records. authorswork_authors是一对多的关系, authors包含大约 700 万条记录, work_authors包含大约 2100 万条记录。

SELECT  t2.author_id, t1.work_id, t2.name 
FROM    work_author AS t1, 
        authors AS t2 
WHERE   t1.author_id = t2.id AND
        t2.name LIKE '%Tolkien%';

Firstly, there is no index at all in the database, ie no primary key or other indexes.首先,数据库中根本没有索引,即没有主键或其他索引。 Then the query on average takes 24 seconds on my machine.然后在我的机器上查询平均需要 24 秒。 When adding index ie making the id-column of authors primary key, but not any index or primary key for the work_author table, the query takes on average 64 seconds on my machine.添加索引时,即创建作者主键的 id 列,而不是work_author表的任何索引或主键,查询在我的机器上平均需要 64 秒。

Secondly, when I add an non-unique index to column author_id the work_author table the query on average takes 4 seconds on my machine.其次,当我向列author_id添加一个非唯一索引时, work_author表的查询在我的机器上平均需要 4 秒。

How can this be the case?怎么会这样? Why is the query taking longer when adding index to one of the attributes used to join than having no index at all?为什么在将索引添加到用于连接的属性之一时查询花费的时间比根本没有索引要长? And then when adding index to the both join keys it executes faster than the other two alternatives.然后在向两个连接键添加索引时,它的执行速度比其他两个选择要快。 Anyone who can explain this?谁能解释一下?

No index can help LIKE '%Tolkien%' .没有索引可以帮助LIKE '%Tolkien%' However, ...然而, ...

Consider adding a FULLTEXT index to authors.name and using考虑将FULLTEXT索引添加到authors.name并使用

MATCH(name) AGAINST('+Tolkein' IN BOOLEAN MODE)

This will run a lot faster.这将运行得更快。

PRIMARY KEYs are important. PRIMARY KEYs很重要。

Using InnoDB is important.使用 InnoDB 很重要。

Do use the JOIN...ON syntax instead of commajoin.请使用JOIN...ON语法而不是逗号。

A many-to-many table is optimized by having two indexes as discussed here: http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table多对多表通过此处讨论的两个索引进行优化: http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table

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

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