1. 程式人生 > >Postgresql 另類的min和max

Postgresql 另類的min和max

測試表請引數,資料量為一千六百萬.

常規方法

explain (analyze,verbose,costs,buffers,timing)
select min(objectid),max(objectid) from test;
--Execution time: 0.190 m

explain (analyze,verbose,costs,buffers,timing)
select min(objectid),max(objectid) from test where num=20;
--Execution time: 0.122 ms

另類的方法

explain (analyze,verbose,costs,buffers,timing)
(select
objectid from test order by objectid limit 1) union all (select objectid from test order by objectid desc limit 1);
--Execution time: 0.156 ms explain (analyze,verbose,costs,buffers,timing) (select objectid from test where num=20 order by objectid limit 1) union all (select objectid from test where num=20
order by objectid desc limit 1);
--Execution time: 0.094 ms explain (analyze,verbose,costs,buffers,timing) select objectid as min,(select objectid from test order by objectid desc limit 1) as max from test order by objectid limit 1; --Execution time: 0.157 ms explain (analyze,verbose,costs,buffers,timing) select
objectid as min,(select objectid from test where num=20 order by objectid desc limit 1) as max from test where num=20 order by objectid limit 1;
-- Execution time: 0.095 ms

雖然提升不是很多,但效能就是從細節中扣出來的