首页 > 解决方案 > Mysql,获取每2列对的最新值

问题描述

这是一个简单的表格

桌子

我只想返回最近的创建日期)唯一的 item_key 和 category_key 对

在这种情况下,请求应返回第 1、3、4 行。1, 3 因为它是唯一的对, 4 因为该行是最近的一对 ["titi" and 3] 然后是第 3 行

这是我的预期结果:

结果

我使用 mysql 5.7 数据库。

谢谢你的帮助

标签: mysql

解决方案


您没有提及您使用的是哪个版本的 MySQL,所以我假设它是现代版本(MySQL 8.x)。

您可以使用该ROW_NUMBER()功能,如:

select *
from (
  select *,
    row_number() over(partition by item_key, category_key 
                      order by creation_date desc) as rn
  from t
) x
where rn = 1

编辑 MySQL 5.x

在 MySQL 5.x 中,您可以执行以下操作:

select *
from t
where (item_key, category_key, creation_date) in (
  select item_key, category_key, max(creation_date)
  from t
  group by item_key, category_key
)

推荐阅读