SQL求最大值的幾種方式

有表如下:

create table students
(sno int,
sname varchar(10),
age int);


insert into students values(1,'AARON',20);
insert into students values(2,'CHUCK',21);
insert into students values(3,'DOUG',20);
insert into students values(4,'MAGGIE',19);
insert into students values(5,'STEVE',22);
insert into students values(6,'JING',18);
insert into students values(7,'BRIAN',21);
insert into students values(8,'KAY',20);
insert into students values(9,'GILLIAN',20);
insert into students values(10,'CHAD',21);

 

求年齡最大的學生?

 

方式一,我的第一反應是使用聚焦函數max,相信很多人和我一樣。

select * from students where age=(select max(age) from students);

 簡單明瞭,兩次全表掃描,成本6

 

方式二,有沒有不使用max的方法來求最大呢?使用自連接加比較。

select * from students 
where age not in (select a.age from students a, students b where a.age< b.age);

 先做笛卡爾集,求年齡比任一個小的,再排除他們。三次全表掃描,成本12

 

方式二的改良

select * from students s1 
where not exists (select 1 from students s2 where s1.age<s2.age);

 兩次全表掃描,成本8

 

方式三,使用窗口函數

select * from (select students.*,max(age)over() oldest from students) 
where age=oldest;

 一次全表掃描,成本3

 

我本人也有些意料之外,沒想到窗口函數威力巨大。

總結:

優先使用窗口函數,然後纔是聚集函數;能用exists,就別用in;儘量別做笛卡爾集。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章