【问题标题】:MySQL - Get the latest record for a given list of column valuesMySQL - 获取给定列值列表的最新记录
【发布时间】:2018-12-28 22:26:00
【问题描述】:

我的表结构如下:

请求表:

 id  insret_time             account id
 ------------------------------------
 1  2018-04-05 08:06:23       abc
 2  2018-09-03 08:14:45       abc
 3  2018-08-13 09:23:34       xyz
 4  2018-08-04 09:25:37       def
 5  2018-08-24 11:45:37       def

我需要查找帐户 ID abc 和 def 的最新记录。我不在乎xyz。

我尝试使用 group by 和 inner join 方法获取结果,但未能成功地将结果限制为我关心的用户列表。 请指教

更新: 感谢大家的反馈。欣赏它!我需要整行作为输出。自自动递增以来,我使用 id 列而不是时间戳来获取最新记录 这是我最终想出的,它给了我需要的输出:

select t.* FROM table t
join (select max(table.id) as maxNum from table 
where account_id in ('abc','def') group by account_id) tm on t.id = tm.maxNum;

【问题讨论】:

  • 只需使用where 条件与group bymax...
  • 向我们展示您的尝试

标签: mysql sql hibernate


【解决方案1】:

我想这就是你要找的东西

  select account_id,max(insret_time)
  from table where account_id in ('abc', 'def')
  group by account_id

【讨论】:

    【解决方案2】:

    您可以使用not in而忽略xyz记录并通过desc下订单:

    select account_id,max(insert_time) from table where account_id not in ('xyz') group by account_id order by id desc
    

    您也可以将!= 运算符仅用于一个表达式:

    select account_id,max(insert_time) from table where account_id!='xyz' group by account_id order by id desc
    

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多