如何使mysql派生表使用索引

时间:2017-06-22 05:40:41

标签: mysql derived-table

MySQL版本5.6.33

我有两个表(文件& 详细信息)到内部联接

文件,有一个名为 idx_record 的索引(record_id)

详细信息,有一个名为 idx_end_org_record 的索引(end_at,org_id,record_id)

explain
SELECT
    id as file_id,
    record_id,
    recording_path
FROM `files`
INNER JOIN
(
    SELECT `details`.`record_id`
    FROM `details` 
    WHERE `details`.`org_id` IN (6231, 6232, 6233, 6234) 
    AND (`details`.`end_at` BETWEEN '2017-05-31 16:00:00' AND '2017-06-13 16:00:00') 
    ORDER BY end_at desc
) as b
    on `files`.record_id = b.record_id 
WHERE (file_name IS NOT NULL )
LIMIT 30

输出如下

+----+-------------+--------------+-------+--------------------+--------------------+---------+------------------+---------+--------------------------+
| id | select_type | table        | type  | possible_keys      | key                | key_len | ref              | rows    | Extra                    |
+----+-------------+--------------+-------+--------------------+--------------------+---------+------------------+---------+--------------------------+
|  1 | PRIMARY     | <derived2>   | ALL   | NULL               | NULL               | NULL    | NULL             | 3844632 | Using where              |
|  1 | PRIMARY     | files        | ref   | idx_record         | idx_record         | 5       | b.record_id      |       1 | Using where              |
|  2 | DERIVED     | details      | range | idx_end_org_record | idx_end_org_record | 11      | NULL             | 3844632 | Using where; Using index |
+----+-------------+--------------+-------+--------------------+--------------------+---------+------------------+---------+--------------------------+

如您所见,<derived2>表未使用任何索引,使此查询花费将近1秒钟完成。

感谢任何帮助!

此外,删除查询中的WHERE (file_name IS NOT NULL )并没有任何区别。

在mysql 5.7中,这个问题甚至不存在,但是目前我正试图在5.6中解决这个问题。

1 个答案:

答案 0 :(得分:2)

我没有看到子查询的重点。特别是,子查询中的ORDER BY毫无意义。如果您将查询编写为两个表之间的直接连接,那么优化器应该能够利用连接列上的索引:

SELECT
id as file_id,
record_id,
recording_path
FROM files f
INNER JOIN details d
    ON f.record_id = d.record_id AND
       d.org_id IN (6231, 6232, 6233, 6234) AND
       d.end_at BETWEEN '2017-05-31 16:00:00' AND '2017-06-13 16:00:00'
WHERE f.file_name IS NOT NULL
ORDER BY <some column>    -- it doesn't make sense most of the time to use LIMIT
LIMIT 30                  -- without ORDER BY

record_id表格中的org_idend_atdetails以及file_name表格中的files上添加索引,应该给你一些改进。