举个例子:
一个表tab里有3个字段:a、b、c,都是integer型,其中a是主键,b、c上都没有索引。
我想取表里b=1而且c最大的记录。现在我们经常有这种需求,一般写法是这样:selete * from tab where b = 1 and c = (select max(c) from tab where b = 1);
在一个六百万数据量、b字段基本上都为1的这种表里,执行时间大概是25秒。请问还有什么高效的写法吗?
一个表tab里有3个字段:a、b、c,都是integer型,其中a是主键,b、c上都没有索引。
我想取表里b=1而且c最大的记录。现在我们经常有这种需求,一般写法是这样:selete * from tab where b = 1 and c = (select max(c) from tab where b = 1);
在一个六百万数据量、b字段基本上都为1的这种表里,执行时间大概是25秒。请问还有什么高效的写法吗?
from(
select a,b,c,row_number() over(partition by b order by c desc) rn from test_abc where b=1
) where rn=1在b上加个索引
你可以在C上建索引
select *
from
(
select *
from
tab
where b=1
order by c
)
rownum=1
FROM (SELECT T.a,
T.b,
T.c,
MAX(T.c) OVER(PARTITION BY T.b) AS SSS
FROM tbl T
WHERE T.b = 1) D
WHERE D.c = D.SSS
可以修改为
where (b,c)=(select 1,max(c) from where b=1)2.很明显,只要在b,c上建立索引可以很高效的完成