繁体   English   中英

为什么这个MySQL查询没有索引会更快?

[英]Why this MySQL query is faster without index?

我无法理解为什么我将MySQL查询更改为不使用索引时运行得更快。

我的第一个查询需要0.236s才能运行:

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

我的第二个查询需要0.147s才能运行:

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

我在site_id,role_id和email列上有一个名为idx_1的唯一索引。

EXPLAIN语句告知它将使用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 |
+----+-------------+-------+------+-------------------------------------+-------+---------+-------------+-------+----------------------------------------------------+

该表有大约110000条记录。

谢谢

更新1:

以下是我的表索引列表:

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

您尚未指定要使用的mysql。 这说明了吗

在MySQL 5.1.17之前,USE INDEX,IGNORE INDEX和FORCE INDEX仅影响在MySQL决定如何在表中查找行以及如何处理联接时使用哪些索引。 它们不影响解析ORDER BY或GROUP BY子句时是否使用索引。

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

暂无
暂无

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

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