如何选择不同列值的最新记录?

Posted

技术标签:

【中文标题】如何选择不同列值的最新记录?【英文标题】:How to select the latest records for distinct column values? 【发布时间】:2019-07-13 20:19:20 【问题描述】:

在我的数据库中,我的配置文件 ID 的状态也有时间戳。我想使用查询获得每个配置文件的最新状态。我怎样才能以最简单的方式做到这一点?

所以 f.e.为:

Id      Profile  Timestamp
-------------------------
1        1       1550588089
2        1       1550588099
3        3       1550588183
4        4       1550588333
5        4       1550588534
6        4       1550588377

我想拥有

Id      Timestamp
-------------------------
2       1550588099
3       1550588183
5       1550588534

【问题讨论】:

哪个 mariadb 版本? 版本 10.2.16 【参考方案1】:

您可以使用相关子查询

DEMO

select id as status, Timestamp
from tablename a where timestamp in (select max(timestamp) from tablename b where a.profile=b.profile )

输出:

tatus   Timestamps
2       1550588099
3       1550588183
5       1550588534

或者你可以使用row_number()

select * from 
(
select *, row_number() over(partition by profile order by timestamp desc) as rn
from tablename
)A where rn=1

【讨论】:

第一个查询有效吗? Max 只给出一个结果行不是吗? @Klyner,你试过了吗?它肯定可以工作 但是可以去掉子查询的GROUP BY。 @Klyner,你可以在这里查看-dbfiddle.uk/… 非常感谢演示!它确实:)【参考方案2】:

使用支持最大dbms的row_number()

 select * from 
(
 select *,row_number() over(partition by Id order by timestamp desc) rn
 from table
) t where t.rn=1

【讨论】:

【参考方案3】:

这个查询:

select profile, max(timestamp) maxtimestamp 
from tablename
group by profile 

返回每个配置文件的所有最大时间戳。 因此,您可以通过将其加入主表来获得所需的内容:

select id, timestamp
from tablename t
inner join (
  select profile, max(timestamp) maxtimestamp 
  from tablename
  group by profile 
) g
on g.profile = t.profile and g.maxtimestamp = t.timestamp

见demo

【讨论】:

以上是关于如何选择不同列值的最新记录?的主要内容,如果未能解决你的问题,请参考以下文章

从具有重复列值的集合中选择第一条记录 C#

如何在 MySQL 中为每个唯一列值选择两条记录作为一行?

SQL - MYSQL 一个查询接收不同列值的设置限制

Ext JS:如何在具有多个列值的网格中查找记录

Hive Bucketing:不同列值的数量大于分桶数量

SQL如何查询出某一列中不同值出现的次数?