[英]how to select with group by user in postgresql
我有两个表的用户和消息。 我想按时间选择用户的消息,并按userId分组。 我使用postgresql,只想选择一条时间已达到最大值的消息。这是我的表和sql查询:
users messages
id name surname e-mail id userId title time token
1 joe joe bla@hotmail.com 1 1 title1 null 1
1 1 title2 null 2
1 1 title3 null 3
1 1 title4 null 4
select *,max(m.time) from users u join messages m on u.id=m.userId group by m.userId
按userId选择消息组时出现SQL错误
我认为您正在寻找:
select *
from messages m
where (m.userId, m.time) in
(
select m.userId,max(m.time)
from users u join messages m
on u.id=m.userId
group by m.userId
);
id userid title time token
-- ------ ------ --------------------------- -----
1 1 title2 2018-09-01T13:37:21.075024Z 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.