从 mysql 数据库中获取最新的更新数据
Get a most recent updated data from mysql database
我需要从 table 中检索每个 ID 的一系列数据。该列的数据或行值需要是第二个最近的值。例如,我有
Table- estimate_record如下
Id value last_updated
1 210 10/2018
1 205 11/2018
1 215 12/2018 -- current
我需要为那个特定的 id =1 获取 205
我用了 Max(value)
,但它变成了 215
,这是不对的。
如果你是 运行 MySQL 8.0,你可以用 window 函数来做到这一点:
select *
from (
select t.*, row_number() over(partition by id order by last_updated desc) rn
from mytable t
) t
where rn = 2
在早期版本中,一个选项使用子查询:
select t.*
from mytable t
where t.last_updated = (
select t1.last_updated
from mytable t1
where t1.id = t.id
order by t1.last_updated desc
limit 1 offset 1
)
我需要从 table 中检索每个 ID 的一系列数据。该列的数据或行值需要是第二个最近的值。例如,我有 Table- estimate_record如下
Id value last_updated
1 210 10/2018
1 205 11/2018
1 215 12/2018 -- current
我需要为那个特定的 id =1 获取 205
我用了 Max(value)
,但它变成了 215
,这是不对的。
如果你是 运行 MySQL 8.0,你可以用 window 函数来做到这一点:
select *
from (
select t.*, row_number() over(partition by id order by last_updated desc) rn
from mytable t
) t
where rn = 2
在早期版本中,一个选项使用子查询:
select t.*
from mytable t
where t.last_updated = (
select t1.last_updated
from mytable t1
where t1.id = t.id
order by t1.last_updated desc
limit 1 offset 1
)