mysql5.7实现ROW |
您所在的位置:网站首页 › mysql查询rownum分组 › mysql5.7实现ROW |
背景
前两天遇到个需求,数据库里相同ID有多条数据,根据update_time取出最新的数据 方案阶段一: 直接用 SELECT * FROM( SELECT t.*, ROW_NUMBER() OVER(PARTITION BY id ORDER BY update_time DESC) updateTime FROM table AS t ) AS latest WHERE updateTime = 1;直接报错了: 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(PARTITION BY merchart_no ORDER BY update_time DESC) t from table' at line 1发现MySQL5.7版本没有over()函数,MySQL8以上版本才有 阶段二: 使用SQL语句实现over函数: select * from (select -- 每行+1 @rownum:=@rownum+1, -- 如果变量的值等于code的值 排名+1, 如果不等于就是1 @rownum:=@rownum+1 rownum,b.id,b.update_time, if(@mno=b.id or (@mno is null and b.id is null), @rank:=@rank+1,@rank:=1) as row_number from (select * from table ORDER BY id,update_time desc) b ) a where -- 排名第一的选出来 a.row_number=1说明: @rownum、@mno、@rank都是MySQL定义的变量 b.id、update_time、table是使用是需要替换的字段和表 整理成公式,可以直接套用: select * from (select @rownum:=@rownum+1 rownum,相同值多条数据的字段,排序的字段, if(@mno=相同值多条数据的字段 or (@mno is null and 相同值多条数据的字段 is null), @rank:=@rank+1,@rank:=1) as row_number from (select * from 表名 ORDER BY 相同值多条数据的字段,排序的字段 desc) b ) a where -- 排名第一的选出来 a.row_number=1记录下,方便下次使用 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |