mysql分析函数的实现

  • 时间:
  • 浏览:2

(select @rownum := 0, @name := null, @rank := 0) a) result where rank<5;

select name, name1, count  from (select b.name, b.name1,b.count,

今天收到同事的一需求,要求实现以下功能:

将会你对下面的select @rownum := 0, @name := null, @rank := 0看不太明白,都还能不能 改写一下sql:

将会上端的sql初次看得人一点想要 你摸不着头脑得话,想要 你看看他的执行计划,想要 从执行计划得到一点执行流程,该sql中最核心的技术点为使用自定义变量来保存sql执行过程中的值:

insert into test values(‘3′,’q’,23);

insert into test values(‘2′,’g’,9);

insert into test values(‘2′,’i’,21);

from test order by name asc, count desc) b) result where rank<4;

insert into test values(‘1′,’c’,4);

if(@name = b.name, @rank := @rank + 1, @rank := 1) as rank,@name:=b.name

insert into test values(‘3′,’p’,22);

insert into test values(‘3′,’r’,42);

from (select name, name1, count    from test order by name asc, count desc) b,

if(@name = b.name, @rank := @rank + 1, @rank := 1) as rank,@name:=b.name

insert into test values(‘2′,’j’,3);

insert into test values(‘2′,’h’,0);

drop table test;

insert into test values(‘3′,’o’,12);

select name, name1, count  from (select b.name, b.name1, b.count,

from (select name, name1, count,@rownum := 0, @name := null, @rank := 0

insert into test values(‘1′,’e’,7);

if(@name = b.name, @rank := @rank + 1, @rank := 1) as rank,@name:=b.name

这条判断得话对下面结果进行处置,并生成rank,将会下面查询的结果中对name做了排序,然后我有@name:=b.name使的相同name值的rank不能递增;

insert into test values(‘2′,’l’,56);

insert into test values(‘1′,’b’,1);;

insert into test values(‘1′,’d’,5);

insert into test values(‘1′,’a’,2);

delete from test;

insert into test values(‘1′,’f’,8);

根据name字段分组,取出改组内的前4项,想要 按照count字段进行降序排序,将会mysql那末oracle中的分析函数,看上去很简单的需求,想要 折腾了许久,还是那末实现,于是乎在网上收罗了一下mysql分析函数是为何么实现的 ,找到了mysql分析函数的处置最好的方式,学习了一下,于是乎把同事的功能实现了;

insert into test values(‘3′,’s’,26);

insert into test values(‘2′,’k’,4);

create table test(name varchar(10),name1 varchar(10),count bigint);

insert into test values(‘3′,’m’,67);

insert into test values(‘3′,’n’,89);