MYSQL-實現ORACLE- row_number() over(partition by ) 分組排序功能最佳化

來源:互聯網
上載者:User

今天看了篇文章,被幾個地方轉載,但是效能不太好,因為不能評論,所以把最佳化思路寫在這裡。

1.確定需求: 根據部門來分組,顯示各員工在部門裡按薪水排名名次.

2.來建立執行個體資料:

drop table if exists heyf_t10;

create table heyf_t10 (empid int ,deptid int ,salary decimal(10,2) );insert into heyf_t10 values(1,10,5500.00),(2,10,4500.00),(3,20,1900.00),(4,20,4800.00),(5,40,6500.00),(6,40,14500.00),(7,40,44500.00),(8,50,6500.00),

(9,50,7500.00);

3. http://www.kaishixue.com/mysql/14.html 文章中SQL的實現

select empid,deptid,salary,rank

from (select heyf_tmp.empid, heyf_tmp.deptid, heyf_tmp.salary, @rownum:=@rownum+1, if(@pdept=heyf_tmp.deptid,@rank:=@rank+1,@rank:=1) as rank, @pdept:=heyf_tmp.deptid from (select empid,deptid,salary from heyf_t10 order by deptid asc ,salary desc ) heyf_tmp, (select @rownum:=0, @pdept:=null,@rank:=0) a ) result;

執行計畫如下

idselect_typetabletypepossible_keyskeykey_lenrefrowsfilteredExtra
1PRIMARY<derived2>ALLNULLNULLNULLNULL9100.00
2DERIVED<derived4>systemNULLNULLNULLNULL1100.00
2DERIVED<derived3>ALLNULLNULLNULLNULL9100.00
4DERIVEDNULLNULLNULLNULLNULLNULLNULLNULLNo tables used
3DERIVEDheyf_t10ALLNULLNULLNULLNULL9100.00Using filesort

如果大資料量直接就掛了。換個思路來寫

select h.`empid`,h.`deptid`,h.`salary`,count(*) as rank
from heyf_t10 as h
left outer join heyf_t10 as r
on h.deptid = r.deptid
and h.`salary`<= r.`salary`
group by h.`empid`,h.`deptid`,h.`salary`
order by h.deptid, h.salary desc;

idselect_typetabletypepossible_keyskeykey_lenrefrowsfilteredExtra
1SIMPLEhALLNULLNULLNULLNULL9100.00Using temporary; Using filesort
1SIMPLErALLNULLNULLNULLNULL9100.00

需要最佳化的時候建立個索引最佳化掉filesort,很直觀,效率也提高了很多。有時候不能太趕需求,遇到複雜的SQL還是讓DBA來最佳化一下。

--EOF--

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.