Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从mysql数据库获取最新更新的数据_Mysql_Sql_Datetime_Greatest N Per Group_Window Functions - Fatal编程技术网

从mysql数据库获取最新更新的数据

从mysql数据库获取最新更新的数据,mysql,sql,datetime,greatest-n-per-group,window-functions,Mysql,Sql,Datetime,Greatest N Per Group,Window Functions,我需要从表中检索每个id的一系列数据。列的数据或行值必须是第二个最新值。例如,我有 表-估计记录如下 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,您可以使用窗口函数: s

我需要从表中检索每个id的一系列数据。列的数据或行值必须是第二个最新值。例如,我有 表-估计记录如下

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,您可以使用窗口函数:

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
)

谢谢,但我正在使用MySQL 5.5。@Sam:好的。我用早期版本的解决方案编辑了我的答案。假设我又添加了两行2 214 12/2018 3 300 11/2019 3 400 12/2019,我需要得到205表示该特定id=1,但300表示id=3。另外,对于那个特定的id,我还需要找出当前更新的id和上次更新的id之间的差异。@Sam:在这里,在发布答案后更改问题不是一个好的做法。我只能推荐你。当然。虽然我有这个帐户几年了,但我很少使用它。我会问另一个问题。
last\u updated
datetime字段还是varchar?