简体   繁体   English

是否在MySql中使用IN Query使用索引?

[英]Is IN Query used index in MySql or not?

I have a query like 我有一个查询

SELECT * FROM Table_name WHERE column1 = '1' AND  column2 IN ('1','2','3');

And index exists on (column1, column2, column3) . 并且索引存在于(column1, column2, column3) Is my above query used index I have created or not? 我上面的查询使用的索引是我创建的还是不是? Basically I am confused with the IN keyword, without this it is using, but with IN I am not sure. 基本上,我对IN关键字感到困惑,没有使用它,但是不确定IN Please explain me. 请给我解释一下。

MySQL can use indexes with IN conditions. MySQL可以使用带有IN条件的索引。 If you only have an index on column2 , it will most likely be used. 如果只有column2上有一个索引,则很有可能会使用它。 If you have indexes on each of column1 and column2 , only one of them can be used, and the query planner will have to decide which one seems better for a particular query. 如果您在column1column2每一个上都有索引,则只能使用其中的一个,查询计划者将必须确定哪个索引对特定查询似乎更好。 If you have a composite index on (column1, column2) then it should be able to use that index to match both columns in the WHERE clause. 如果您在(column1, column2)上有一个复合索引(column1, column2)则它应该能够使用该索引来匹配WHERE子句中的两列。

MySQL is capable of using indices with IN .. now, is MySQL using indices in the particular query? MySQL是能够使用与指数的IN 。现在, 利用指数在特定查询的MySQL? Well, ask the query planner ! 好吧, 问查询计划者

In this case an index over (column1, column2, ..) could be used - because all the leftward components have been satisfied. 在这种情况下,指数超过(column1, column2, ..) 可以用来-因为所有的组件向左已满足。 That is, an index seek could be done on column1 (for = ), and then column2 (for IN ). 也就是说,可以在column1(对于= )上,然后在column2(对于IN )上完成索引查找。 But again, ask the query planner as unexpected plans are not unheard of; 但是,再次询问查询计划者,因为并非没有听说过意外的计划。 just because the query planner could choose an index doesn't mean that it will. 仅仅因为查询计划者可以选择索引并不意味着就可以。

See EXPLAIN , for how to ask: 请参阅EXPLAIN ,以了解如何询问:

When EXPLAIN is used with an explainable statement, MySQL displays information from the optimizer about the statement execution plan. 当EXPLAIN与可解释的语句一起使用时,MySQL将显示来自优化程序的有关语句执行计划的信息。 That is, MySQL explains how it would process the statement, including information [like index usage] about how tables are joined and in which order .. 也就是说,MySQL解释了它将如何处理该语句,包括有关表如何连接以及顺序如何的信息(例如索引用法)。

.. With the help of EXPLAIN, you can see where you should add indexes to tables so that the statement executes faster by using indexes to find rows. ..在EXPLAIN的帮助下,您可以看到应该在哪里向表添加索引,以便通过使用索引查找行来使语句更快地执行。

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

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