請注意,T和T1都指向同一個表。 我們試圖檢索最大值,並在檢索最大值時,我們 對那些具有相同columnC值的行感興趣。如何優化包含max的SQL查詢?
select *
from table T
where T.columnA in (0,1,2,3)
and T.columnB = (select max(T1.columnB)
from table T1
where T1.columnC = T.columnC)
請注意,T和T1都指向同一個表。 我們試圖檢索最大值,並在檢索最大值時,我們 對那些具有相同columnC值的行感興趣。如何優化包含max的SQL查詢?
select *
from table T
where T.columnA in (0,1,2,3)
and T.columnB = (select max(T1.columnB)
from table T1
where T1.columnC = T.columnC)
這種類型的查詢通常是更有效的利用窗口函數:
select *
from (
select *,
max(columnb) over (partition by columnc) as max_b
from the_table
where columna in (0,1,2,3)
) t
where columnb = max_b;
如果columna
條件是非常有選擇性的在該列的索引會有所幫助。如果你改變columna in (0,1,2,3)
到columna between 0 and 3
不知道你想去的地方做一些優化可能會產生更有效的計劃(該層)的columnA過濾器,但也許是這樣的:
Select tt1.* from table tt1
inner join
(
select * from
table t1
inner join
(select max(T0.columnB) max_columnB
from table t0) t2
on t1.columnB = t2.max_columnB
) tt2
on tt1.columnC = tt2.columnC
Where tt1.columnA in (0,1,2,3)
是需要columnA索引,並且columnB和columnC運行得很快。
a_horse_sith_no_name是正確的,窗口函數通常是更好的方法。無論窗口函數或查詢如何,索引都會有所幫助。
特別是,您需要T(columnc, columnb)
和T(columnA)
上的索引。這是兩個單獨的索引。 SQL優化器應該能夠利用這些索引同時用於查詢和窗口函數方法。
這與Hibernate有什麼關係?刪除標籤。 –
你正在使用哪些DBMS? Postgres的?甲骨文? DB2?火鳥? –
@a_horse_with_no_name:postgres,DB2,Oracle - 通過hibernate。 –