How to get the latest record in each group using GROUP BY?(如何使用GROUP BY获取每个组中的最新记录?)
问题描述
假设我有一个名为 messages 的表,其中包含列:
Let's say I have a table called messages with the columns:
id | from_id | to_id | subject | message | timestamp
我只想从每个用户那里获取最新消息,就像您在深入了解实际线程之前在 Facebook 收件箱中看到的一样.
I want to get the latest message from each user only, like you would see in your FaceBook inbox before you drill down into the actual thread.
这个查询似乎让我接近我需要的结果:
This query seems to get me close to the result I need:
SELECT * FROM messages GROUP BY from_id
然而,查询给我的是来自每个用户的最旧的消息,而不是最新的消息.
However the query is giving me the oldest message from each user and not the newest.
我无法弄清楚这一点.
推荐答案
你应该找出每组(子查询)中最后一个timestamp的值,然后把这个子查询加入到表中 -
You should find out last timestamp values in each group (subquery), and then join this subquery to the table -
SELECT t1.* FROM messages t1
JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages GROUP BY from_id) t2
ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp;
这篇关于如何使用GROUP BY获取每个组中的最新记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用GROUP BY获取每个组中的最新记录?
基础教程推荐
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 无法解决整理冲突 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
