【问题标题】:How to group by obtaining the latest record如何通过获取最新记录进行分组
【发布时间】:2022-06-14 16:37:55
【问题描述】:

我有这些表:

users: [id, name]
user_profiles: [id, user_id, created_at]

这些条目:

insert into users values(1, 'jack')
insert into users values(2, 'paul')
insert into users values(3, 'mary')

insert into user_profiles values(1, 1, '2022-01-01 10:00:00')
insert into user_profiles values(2, 1, '2022-01-01 11:00:00')
insert into user_profiles values(3, 2, '2022-01-01 12:00:00')
insert into user_profiles values(4, 2, '2022-01-01 13:00:00')
insert into user_profiles values(5, 2, '2022-01-01 14:00:00')
insert into user_profiles values(6, 3, '2022-01-01 15:00:00')

我需要的是从按 user_id 分组的 user_profiles 中获取行。 但是,我需要在 user_profiles 中获取用户的最新条目。

这个查询:

select user_profiles.*, users.name 
from user_profiles
left join users on users.id = user_profiles.user_id
group by user_profiles.user_id
order by user_profiles.created_at desc /*Or even asc*/

会给我这个结果列表:

id   | user_id | created_at          | name |
+------+---------+---------------------+------+
|    6 |       3 | 2022-01-01 15:00:00 | mary |
|    3 |       2 | 2022-01-01 12:00:00 | paul |
|    1 |       1 | 2022-01-01 10:00:00 | jack |

如您所见,user_id = 1 显示最旧的条目。不是最新的。 相反,对于用户“jack”,它应该选择 created_at = 2022-01-01 11:00:00 的行 我需要做什么?是不是应该使用MAX函数?

【问题讨论】:

  • 你用的是什么MySQL?

标签: mysql


猜你喜欢
  • 2021-12-16
  • 2019-07-03
  • 2022-12-04
  • 1970-01-01
  • 2018-10-17
  • 2012-04-10
  • 2012-12-14
  • 2021-12-14
  • 2014-05-07
相关资源
最近更新 更多