我有一个数据库方案,看起来像这样(参见http://sqlfiddle.com/#![/p]:
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"列表中与"dataA"对应的最大"dataB"
SELECT * FROM t a WHERE dataB = (SELECT MAX(dataB) FROM t b WHERE b.dataA = a.dataA)
它可以正常工作,但是它可能需要90秒才能在我的数据集上运行。
如何提高查询的性能?
甚至对于重复的数据aa, 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
的行"。