简体   繁体   中英

MySQL select statement is not using the index

I have one table called T. It has 4 attributes: x, y, z and w.

I loaded the table with data. Then, created an index on x, and also another index on 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.

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. 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.

So, is the AND in the condition prevents from using the indexes or what exactly I have done wrong here?

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

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.

MySQL can only use 1 index per table in a query. 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.

@Mojtaba's answer explains how to create a multi-column index that MySQL will use in your scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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