简体   繁体   English

MySQL select语句没有使用索引

[英]MySQL select statement is not using the index

I have one table called T. It has 4 attributes: x, y, z and w. 我有一个名为T的表。它有4个属性:x,y,z和w。

I loaded the table with data. 我在表中加载了数据。 Then, created an index on x, and also another index on y. 然后,在x上创建索引,在y上创建另一个索引。

Now, when I submit this query: 现在,当我提交此查询时:

select count(*) from T where x <= 10 and y <=100;

I assume that index x and index y will be used. 我假设将使用索引x和索引y。

However, that does not happen! 但是,这不会发生!

When I use the command EXPLAIN before the select statements, it shows index x and y as " possible_keys " BUT under the column " key " there is NULL. 当我在select语句之前使用命令EXPLAIN时,它将索引x和y显示为“ possible_keys ”,而在“ key ”列下则为NULL。 That means no indexes were used. 这意味着没有使用索引。

Now, if I submit this query: 现在,如果我提交此查询:

select count(*) from T where x<=50;

Then MySQL uses the index x, as the EXPLAIN command shows. 然后MySQL使用索引x,如EXPLAIN命令所示。

So, is the AND in the condition prevents from using the indexes or what exactly I have done wrong here? 那么,条件中的AND是否会阻止使用索引或者我在这里做错了什么?

Regards! 问候!

You need to index x and y together, More info here: http://dev.mysql.com/doc/refman/5.5/en/multiple-column-indexes.html 您需要将x和y索引在一起,更多信息请访问: http//dev.mysql.com/doc/refman/5.5/en/multiple-column-indexes.html

You can simply run this query : 您只需运行此查询:

ALTER TABLE `your_table_name_here` 
ADD INDEX `IDX_COMB_XY` (`x` ASC, `y` ASC) ;

Now run Explain and you will see IDX_COMB_XY will be used. 现在运行Explain,您将看到将使用IDX_COMB_XY。

MySQL can only use 1 index per table in a query. MySQL在查询中每个表只能使用1个索引。 When there is more than index to choose from, MySQL will take an educated guess as to which one will be most beneficial, based on cardinality, memory requirements, number of records, etc. 当有多个索引可供选择时,MySQL将根据基数,内存要求,记录数等,采取有根据的猜测,哪一个最有益。

@Mojtaba's answer explains how to create a multi-column index that MySQL will use in your scenario. @ Mojtaba的答案解释了如何创建MySQL将在您的场景中使用的多列索引。

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

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