mysql 实现类似开窗函数的功能

mysql8 已经支持开窗函数 https://dev.mysql.com/doc/refman/8.0/en/window-functions.html

————————————————

sql server 的开窗函数

http://www.cnblogs.com/zihunqingxin/p/3638857.html

 

mysql8 之前的版本不支持开窗函数

 

目的,取每个channel 按created_on 倒序排的前20条

 

示例如下(有部分冗余数据)

select id,url,channel,created_on,rank 
from(
    select id,url,channel,created_on,rank 
    from (select article_tmp.id,url,article_tmp.channel,article_tmp.created_on,@rownum:=@rownum+1 ,
          if(@pdept=article_tmp.channel,@rank:=@rank+1,@rank:=1) as rank,
          @pdept:=article_tmp.channel
          from (
                select id,url,channel,created_on 
                from article order by channel asc ,created_on desc
               ) article_tmp ,
               (select @rownum :=0 , @pdept := null ,@rank:=0) a 
    ) result
)t where rank<=20;

 

最核心的部分是

select article_tmp.id,url,article_tmp.channel,article_tmp.created_on,@rownum:=@rownum+1 ,
          if(@pdept=article_tmp.channel,@rank:=@rank+1,@rank:=1) as rank,
          @pdept:=article_tmp.channel
          from (
                select id,url,channel,created_on 
                from article order by channel asc ,created_on desc
               ) article_tmp

 

原理是按channel 和 created_on 排序

两个临时变量

pdept

rank

pdept 指向channel

 

游标(这么说不准确,就是个遍历的过程)下移的过程中

pdept 未变,则rank++

若pdept 变化,则表示是新的channel  rank归0 

 

最后按取rank 的top N条数据 即可

select article_tmp.id,url,article_tmp.channel,article_tmp.created_on,@rownum:=@rownum+1 ,
          if(@pdept=article_tmp.channel,@rank:=@rank+1,@rank:=1) as rank,
          @pdept:=article_tmp.channel
          from (
                select id,url,channel,created_on 
                from article order by channel asc ,created_on desc
               ) article_tmp

posted @ 2017-04-19 17:12  cclient  阅读(2806)  评论(0编辑  收藏  举报