简体   繁体   中英

Why this MySQL query is faster without index?

I am having trouble understanding why my MySQL query runs faster when I change it to use no indexes.

My first query takes 0.236s to run:

SELECT 
    u.id, 
    u.email, 
    CONCAT(u.first_name, ' ', u.last_name) AS u_name
FROM
    tbl_user AS u
WHERE
    u.site_id=1
    AND u.role_id=5
    AND u.removed_date IS NULL
ORDER BY 
    u_name ASC 
LIMIT 0, 20

My second query takes 0.147s to run:

SELECT 
    u.id, 
    u.email, 
    CONCAT(u.first_name, ' ', u.last_name) AS u_name
FROM
    tbl_user AS u USE INDEX () 
WHERE
    u.site_id=1
    AND u.role_id=5
    AND u.removed_date IS NULL
ORDER BY 
    u_name ASC 
LIMIT 0, 20

I have a unique index named idx_1 on columns site_id, role_id and email.

The EXPLAIN statement tells that it will use idx_1.

+----+-------------+-------+------+-------------------------------------+-------+---------+-------------+-------+----------------------------------------------------+
| id | select_type | table | type | possible_keys                       | key   | key_len | ref         | rows  | Extra                                              |
+----+-------------+-------+------+-------------------------------------+-------+---------+-------------+-------+----------------------------------------------------+
|  1 | SIMPLE      | u     | ref  | idx_1,idx_import,tbl_user_ibfk_2    | idx_1 | 8       | const,const | 55006 | Using index condition; Using where; Using filesort |
+----+-------------+-------+------+-------------------------------------+-------+---------+-------------+-------+----------------------------------------------------+

The table has about 110000 records.

Thanks

UPDATE 1:

Below is the list of my table indexes:

Name                Fields                      Type    Method
---------------------------------------------------------------
idx_1               site_id, role_id, email     Unique  BTREE
idx_import          site_id, external_id        Unique  BTREE
tbl_user_ibfk_2     role_id                     Normal  BTREE
tbl_user_ibfk_3     country_id                  Normal  BTREE
tbl_user_ibfk_4     preferred_country_id        Normal  BTREE
---------------------------------------------------------------

You haven't specified which mysql you are using. Does this explain it

Prior to MySQL 5.1.17, USE INDEX, IGNORE INDEX, and FORCE INDEX affect only which indexes are used when MySQL decides how to find rows in the table and how to process joins. They do not affect whether an index is used when resolving an ORDER BY or GROUP BY clause.

from https://dev.mysql.com/doc/refman/5.1/en/index-hints.html

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