SELECT archive.id, archive.file, archive.create_timestamp, archive.spent
FROM archive LEFT JOIN submissions ON archive.id = submissions.id
WHERE submissions.id is NULL
AND archive.file is not NULL
AND archive.create_timestamp < DATE_SUB(NOW(), INTERVAL 6 month)
AND spent = 0
ORDER BY archive.create_timestamp ASC LIMIT 10000
EXPLAIN结果:
+----+-------------+--------------------+--------+--------------------------------+------------------+---------+--------------------------------------------+-----------+--------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------------------+--------+--------------------------------+------------------+---------+--------------------------------------------+-----------+--------------------------------------+
| 1 | SIMPLE | archive | range | create_timestamp,file_in | create_timestamp | 4 | NULL | 111288502 | Using where |
| 1 | SIMPLE | submissions | eq_ref | PRIMARY | PRIMARY | 4 | production.archive.id | 1 | Using where; Using index; Not exists |
+----+-------------+--------------------+--------+--------------------------------+------------------+---------+--------------------------------------------+-----------+--------------------------------------+
我已经尝试过使用索引来存档表:
USE INDEX (create_timestamp,file_in)
归档表很大,约有150万条记录。
非常感谢任何有关加快此查询的帮助。
答案 0 :(得分:1)
您想要使用复合索引。对于此查询:
create index archive_file_spent_createts on archive(file, spent, createtimestamp);
在这样的索引中,您希望where
条件=
首先出现,然后是最多一列不等式。在这种情况下,我不确定MySQL是否会使用order by
的索引。
这假设where
条件确实会显着减小数据的大小。