createindex user_login_date on user_login_record (group_id, user_id, machine_id, login_date desc);
比较结果
max
1 2 3 4 5 6
explain (analyze, buffers, costs) selectmax(login_date) from user_login_record wheregroup_id='312bb069-fd27-4822-885d-c3ac67bfd8a1' and user_id='952bd155-06b3-4792-82ec-4b86d06c86a7' and machine_id='C635F8F44F1960778CE58869DF10150D';
1 2 3 4 5 6 7 8 9 10 11
QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Aggregate (cost=2.84..2.85 rows=1 width=8) (actual time=0.143..0.143 rows=1 loops=1) Buffers: shared hit=72 -> Index Only Scan using user_login_date on user_login_record (cost=0.41..2.84 rows=1 width=8) (actual time=0.050..0.126 rows=98 loops=1) Index Cond: ((group_id = '312bb069-fd27-4822-885d-c3ac67bfd8a1'::bpchar) AND (user_id = '952bd155-06b3-4792-82ec-4b86d06c86a7'::bpchar) AND (machine_id = 'C635F8F44F1960778CE58869DF10150D'::bpchar)) Heap Fetches: 98 Buffers: shared hit=72 Planning Time: 0.139 ms Execution Time: 0.163 ms (8 rows)
order by … desc limit 1
1 2 3 4 5 6 7 8
explain (analyze, buffers, costs) select login_date from user_login_record wheregroup_id='312bb069-fd27-4822-885d-c3ac67bfd8a1' and user_id='952bd155-06b3-4792-82ec-4b86d06c86a7' and machine_id='C635F8F44F1960778CE58869DF10150D' orderby login_date desc limit1
1 2 3 4 5 6 7 8 9 10 11
QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Limit (cost=0.41..2.84 rows=1 width=8) (actual time=0.042..0.042 rows=1 loops=1) Buffers: shared hit=4 -> Index Only Scan using user_login_date on user_login_record (cost=0.41..2.84 rows=1 width=8) (actual time=0.041..0.041 rows=1 loops=1) Index Cond: ((group_id = '312bb069-fd27-4822-885d-c3ac67bfd8a1'::bpchar) AND (user_id = '952bd155-06b3-4792-82ec-4b86d06c86a7'::bpchar) AND (machine_id = 'C635F8F44F1960778CE58869DF10150D'::bpchar)) Heap Fetches: 1 Buffers: shared hit=4 Planning Time: 0.124 ms Execution Time: 0.057 ms (8 rows)
结论
两个都利用了索引,但利用方式有所不同,max没有利用login_date字段的排序,最后对符合条件的98条数据进行了筛选(rows=98 loops=1);order by limit 1的sql则依旧利用了索引中的 login_date 字段,只取了一套数据(rows=1 loops=1)。 虽然这次max没多一次循环,但由于多了多条记录,相比另外一个sql性能降低了很多。