Postgresql
如何優化請求
使用 Postgresql 執行一個 sql 請求的時間是 Oracle 的 10 倍。我們如何使用 Postgresql 加快查詢速度?
請求如下:
select t1.c1, t1.c2 from MyTable t1 where t1.c3='string' and t1.c2=(select max(t2.c2) from MyTable t2 where t2.c4=t1.c4);
完整的查詢:
select t1.c1, t1.c2 from MyTable t1 left outer join Table t3 on t1.c1=t3.c1 where t1.c3='string' and t1.c2=(select max(t2.c2) from MyTable t2 where t2.c4=t1.c4);
在 Postgres 中,這種類型的查詢在使用完成時效率更高
distinct on ()
select distinct on (c1) t1.c2, t1.c3 from MyTable t1 where MyTable.c4='string' order by c1, c3 desc;
或者使用標準 SQL 和視窗函式:
select * from ( select t1.c2, t1.c3, row_number() over (partition by c1 order by c3 desc) as rn from MyTable t1 where t1.c2='string' and t1.c4 is null ) t where rn = 1;
如果您無法更改查詢,因為這是由混淆層(又名“ORM”)生成的,那麼將列添加
c3
到索引idx_multi_c2_c4
並在其上創建索引(c1,c3)
可能會有所幫助。