mysql - Mysql,获取每2列对的最新值
问题描述
这是一个简单的表格
我只想返回最近的创建日期)唯一的 item_key 和 category_key 对
在这种情况下,请求应返回第 1、3、4 行。1, 3 因为它是唯一的对, 4 因为该行是最近的一对 ["titi" and 3] 然后是第 3 行
这是我的预期结果:
我使用 mysql 5.7 数据库。
谢谢你的帮助
解决方案
您没有提及您使用的是哪个版本的 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
)
推荐阅读
- typescript - 如何根据通用类型“T”初始化 TypeORM 存储库?
- typescript - 尝试扩充界面时,历史没有定义功能
- mongodb - MongoDB - 索引前缀如何工作?
- scrapy - 需要将 Scrapy 回调方法数据返回给调用函数
- javascript - 如何将 hexlified 二进制数据转换为 unicode 字符串
- javascript - 使用过滤器过滤数据表中的特定月份
- intellij-idea - Scalatest 在 Intellij 中与 Scala 2.13.0 一起工作需要什么?
- networking - 如何使用 nodejs 应用程序在两个 pod 之间进行通信
- swift - 当应用程序被“杀死”时,尝试将我的计时器保存到 UserDefaults
- powershell - 读取 CSV 文件,然后拆分值并创建一个全局变量