背景
前两天遇到个需求,数据库里相同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
记录下,方便下次使用

————————————————
版权声明:本文为CSDN博主「北极熊55555」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/shen_xbo/article/details/120451733