列更改时选择一行

时间:2019-02-11 17:16:15

标签: mysql sql

我有一个表,用于存储对象何时更改以及何时被标记。

id  name   markedAt    updatedAt
1   X      2019-01-01  2019-01-01
2   x2     2019-01-01  2019-01-02
3   x2     null        2019-01-03
4   x2     2019-01-04  2019-01-04
5   x3     2019-01-04  2019-01-05
#1 - the object was marked and updated
#2 - the object was updated
#3 - was unmarked
#4 - was marked again
#5 - was updated

如何编写查询以检索上次标记对象时的行。在这种情况下,我需要第4行。

2 个答案:

答案 0 :(得分:1)

您可以在联接中对maxmarketAt使用子查询

    select m.* from  my_table m
    inner join  (
    select name, max(markedAt) max_mark
    from my_table
    group by name 
    ) t on t.markedAt = m.markedAt and t.name = m.name 

每个名称的此应返回值.. 如果只需要name = x2,则在其中添加适当的位置

    select m.* from  my_table m
    inner join  (
    select name, max(markedAt) max_mark
    from my_table
    group by name 
    ) t on t.markedAt = m.markedAt and t.name = m.name 
    where name  = 'x2'

答案 1 :(得分:0)

您首先需要为每个具有分组依据的对象获取最长日期where markedat = updatedat,然后加入主表:

select t.* 
from  tablename t
inner join  (
  select 
    name, 
    max(markedat) maxmarkedat
  from tablename 
  where 
    markedat = updatedat
  group by name 
) g 
on g.maxmarkedat = t.updatedat and g.maxmarkedat = t.markedAt and g.name = t.name