簡體   English   中英

SQL查詢性能優化 - 獲取相應A的max(B)

[英]SQL query performance optimisation - fetching max(B) for corresponding A

我有一個看起來像這樣的數據庫方案(請參閱http://sqlfiddle.com/#!2/4c9b4/1/0 ):

 create table t( id int,  dataA int, dataB int);
 insert into t select 1 ,1 ,1;
 insert into t select 2 ,1 ,2;
 insert into t select 3 ,1 ,3;
 insert into t select 4 ,2 ,1;
 insert into t select 5 ,2 ,2;
 insert into t select 6 ,2 ,4;
 insert into t select 7 ,3 ,1;
 insert into t select 8 ,3 ,2;
 insert into t select 9 ,4 ,1;

以及一個SQL查詢,用於獲取與“dataA”對應的最大“dataB”的“dataA”列表

SELECT * FROM t a WHERE dataB = (SELECT MAX(dataB) FROM t b WHERE b.dataA = a.dataA)

它工作正常,但在我的數據集上運行最多可能需要90秒。

如何提高此查詢的性能?

也許MySQL一次又一次地執行子查詢,即使對於重復的數據也是如此。 以下語句只為每個dataA找到一次max(dataB)。 其余的是一個簡單的連接。 希望這更快。

select t.*
from t
join (select dataA, max(dataB) as maxDataB from t group by dataA) max_t
  on t.dataA = max_t.dataA and t.dataB = max_t.maxDataB;

編輯:這是你的SQL小提琴: http//sqlfiddle.com/# !2/4c9b4/2。

MySQL不能很好地進行聚合。 首先要嘗試的是索引:

create index t_dataA_dataB on t(dataA, dataB);

這可能會解決問題。 第二個是使用以下技巧:

select a.*
from t a
where not exists (select 1
                  from t a2
                  where a2.dataA = a.dataA and
                        a2.dataB > a.dataB
                 );

這些將“讓我最大”,以等價的:“給我所有的行t那里有長着相同的,行dataA和更大的dataB ”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM