暂无图片
Mysql关于group by添加索引的疑问
我来答
分享
佳佳
2021-12-20
Mysql关于group by添加索引的疑问

SQL如下:

SELECT status_code,

ware_code ,

customer_code

FROM   table_name

WHERE create_time >= '2021-01-23'

AND create_time <= '2021-01-24'

AND  ware_code IN ( 'SHANGHAI' , 'BEIJING' ) 

GROUP BY customer_code, ware_code , status_code;

我添加了如下索引,首先用create_time和ware_code 过滤了结果(ICP),然后,把group by 剩余2列customer_code, status_code也添加到索引中,可以用到覆盖索引(不用回表去取这两列的值进行group by),思路对吗?

alter table table_name add index idx_dba(create_time,ware_code,customer_code,status_code);

还是说只要(create_time,ware_code)就行?group by 回表去做。

我来答
添加附件
收藏
分享
问题补充
3条回答
默认
最新
chengang

所谓最好的三星索引
1、过滤性好,能过滤掉较多的行
2、索引覆盖
3、SQL的排序也刚好是索引的排序

满足以上三点,就是最好的三星索引了。
但从你的SQL来看。1与3肯定不能同时满足了。
要么满足1,2, 要么满足2,3

但当底是排序对你这个SQL性能影响大还是过滤,这个要根据实际的数据来看。

你上面的索引就是以满足1,2来的。
不过如果建alter table table_name add index idx_dba(create_time,ware_code,customer_code,status_code);
也可以试试把 ware_code 放在最左试一试
alter table table_name add index idx_dba(ware_code,create_time,customer_code,status_code); 这样可以让过滤key 实现前两个字段过滤。

暂无图片 评论
暂无图片 有用 0
暂无图片
Uncopyrightable

感觉使用between and更合适些,索引使用还是通过explain验证下

暂无图片 评论
暂无图片 有用 0
薛晓刚

我觉得你alter table table_name add index idx_dba(create_time,ware_code)这样就行。

你两个都建立上,看看用哪个?

理论上你一天数据而已,回表也没多少东西

暂无图片 评论
暂无图片 有用 0
回答交流
提交
问题信息
请登录之后查看
邀请回答
暂无人订阅该标签,敬请期待~~
暂无图片墨值悬赏