mysql分析函数的实现

  • 时间:
  • 浏览:2

delete from test;

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

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

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

不可能 底下的sql初次看过或者 刚刚摸不着头脑一段话,刚刚看看他的执行计划,或者从执行计划得到或者 执行流程,该sql中最核心的技术点为使用自定义变量来保存sql执行过程中的值:

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

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

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

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

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

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

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

这条判断一段话对下面结果进行处里,并生成rank,不可能 下面查询的结果中对name做了排序,什么都@name:=b.name使的相同name值的rank促使递增;

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

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

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(‘3′,’m’,67);

根据name字段分组,取出改组内的前4项,或者按照count字段进行降序排序,不可能 mysql这样 oracle中的分析函数,看上去很简单的需求,或者折腾了许久,还是这样 实现,于是乎在网上收罗了一下mysql分析函数是为社 实现的 ,找到了mysql分析函数的处里土法子,学习了一下,于是乎把同事的功能实现了;

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

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

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

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

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

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

drop table test;

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

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

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

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

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

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

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

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

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

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