描述:业务需要查表,该表大约不到四个G,总行数900w条,一个简单的去重的条件查询需要一分钟四十秒,这是不能忍受的。
原语句:耗时1m40s
select count(DISTINCT sip) from mining_machine where mining_pool='YES';
优化措施:
1:首先想到加索引,索引顺序也很重要,根据sql解析顺序 where 解析在前。
create index count_sip on public.mining_machine(mining_pool,sip);
2:优化语句,将distinct 变成group by 来表示,distinct会将重复的key在扫描一遍。
select count(*) from (select sip from mining_machine where mining_pool ='YES' group by sip ) t ;
:结论:原语句1m36s ;建立组合索引后 17s ; sql 优化后 536ms。