一个分享WordPress、Zblog、Emlog、Typecho等主流博客的教程网站!
当前位置:网站首页 > 其他相关教程 > 正文

sql获取最大值那种方法最快

作者:xlnxin发布时间:2023-09-04分类:其他相关教程浏览:247


导读:  求年龄最大的学生?  方式一,使用聚合函数max,相信很多人第一反应。    select*fromstudentswhereage=(sel...

  求年龄最大的学生?

  方式一,使用聚合函数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;尽量别做笛卡尔集。