我有这张表,我正在尝试从中进行选择。该查询需要 2 分钟才能运行 400 万条记录。我不确定我还能从这个查询中挤出多少。
SELECT c.fk_id, c.from_date, c.fk_pb, MIN(o.from_date) AS to_date
FROM TABLE_X c
INNER JOIN TABLE_X o ON c.fk_id = o.fk_id AND c.fk_pb = o.fk_pb
WHERE o.from_date > c.from_date
GROUP BY c.fk_id, c.from_date, c.fk_pb
from_date、fk_pb 和 fk_id 上已有索引。
架构是这样的。
+-----------------------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------------+---------------+------+-----+---------+-------+
| FK_ID | int(11) | YES | MUL | NULL | |
| FK_PB | int(11) | YES | MUL | NULL | |
| FROM_DATE | date | YES | MUL | NULL | |
| TO_DATE | date | YES | | NULL | |
+-----------------------------+---------------+------+-----+---------+-------+
我知道我根本不应该在 MySQL 中使用自联接,但是数据是这样的,我试图找到从这个表中选择和更新的最佳方法。如果我还能做些什么来让这个更快,那就太好了。
非常感谢。
更新
+----+-------------+-------+------+----------------------------------------------------------------------+-------------------------+---------+----------------------------------------+---------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+----------------------------------------------------------------------+-------------------------+---------+----------------------------------------+---------+----------------------------------------------+
| 1 | SIMPLE | c | ALL | IDX_FK_PB,IDX_FK_ID,IDX_FRM_DATE | NULL | NULL | NULL | 4527750 | Using where; Using temporary; Using filesort |
| 1 | SIMPLE | o | ref | IDX_FK_PB,IDX_FK_ID,IDX_FRM_DATE | IDX_FK_ID | 5 | db.c.FK_ID | 110 | Using where |
+----+-------------+-------+------+----------------------------------------------------------------------+-------------------------+---------+----------------------------------------+---------+----------------------------------------------+