我有以下表结构:
请求表:
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列而不是timestamp来获取最新记录,因为它自动递增这是我最终想出的,它给了我需要的输出:
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;
我想这就是你要找的东西
select account_id,max(insret_time)
from table where account_id in ('abc', 'def')
group by account_id
仅使用where
获取insert_time
和in
的最大值,仅包括'abc','def':
select t.* from tablename as t where
t.accountid in ('abc', 'def') and
t.insert_time = (select max(insert_time) from tablename where tablename.accountid = t.accountid)
您可以使用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
我希望它有帮助:)