【发布时间】:2017-11-25 05:41:27
【问题描述】:
MySQL 版本 5.6.33
我有两个表(files & details)要进行内部连接
表files,有一个名为idx_record(record_id)
的索引表details,有一个名为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 中解决这个问题。
【问题讨论】:
标签: mysql derived-table