我有一个有几百万行数据的表。我在 id 上有一个主键,在 col2、col3、col4 和 my_date(称为 comp_indx)上有一个复合唯一键。示例数据显示在这里...
id col2 col3 col4 my_date col5 col6 col7
1 1 1 1 2020-01-03 02:00:00 a 1 a
2 1 2 1 2020-01-03 01:00:00 b 2 1
3 1 3 1 2020-01-03 03:00:00 c 3 b
4 2 1 1 2020-02-03 01:00:00 d 4 2
5 2 2 1 2020-02-03 02:00:00 e 5 c
6 2 3 1 2020-02-03 03:00:00 f 6 3
7 3 1 1 2020-03-03 03:00:00 g 7 d
8 3 2 1 2020-03-03 02:00:00 h 8 4
9 3 3 1 2020-03-03 01:00:00 i 9 e
如果我执行以下查询...
SELECT col2, col3, max(my_date)
FROM table
where col4=1 and my_date <= '2001-01-27'
group by col2, col3
...查询非常高效,运行解释命令显示...
select_type type key key_len rows Extra
----------- ----- --------- ------- ---- -------------------------------------
SIMPLE range comp_indx 11 669 Using where; Using index for group-by
但是,如果我运行类似的命令(只请求更多的列——没有一个是索引的一部分),例如……
SELECT col2, col3, max(my_date), col5, col7
FROM table
where col4=1 and my_date <= '2001-01-27'
group by col2, col3
...然后性能立即下降,如果我再次运行 explain 命令,我会...
select_type type key key_len rows Extra
----------- ----- --------- ------- ------- -----------
SIMPLE index comp_indx 11 5004953 Using where
我可以看到类型已经从范围变为索引,并且我可以看到索引不再用于分组依据。
我试图理解为什么会这样,更重要的是,我该如何解决这个问题?