我有两个表中的用户数据,如
1. USERID | USERPOSTID
2. USERPOSTID | USERPOST | LAST_EDIT_TIME
如何获取每个用户的上次修改过的帖子及其时间?假设每个用户有5个帖子,每个帖子至少编辑一次。
我是否必须编写循环遍历每个用户,找到带MAX的USERPOST(LAST_EDIT_TIME)然后收集值?我尝试过GROUP BY,但我不能将USERPOSTID或USERPOST放在聚合函数中。 TIA。
答案 0 :(得分:1)
似乎这样的事情应该有效:
create table users(
id serial primary key,
username varchar(50)
);
create table posts(
id serial primary key,
userid integer references users(id),
post_text text,
update_date timestamp default current_timestamp
);
insert into users(username)values('Kalpit');
insert into posts(userid,post_text)values(1,'first test');
insert into posts(userid,post_text)values(1,'second test');
select *
from users u
join posts p on p.userid = u.id
where p.update_date =
( select max( update_date )
from posts
where userid = u.id )
答案 1 :(得分:0)
您可以在此处使用windowing function:
select
USERID
, USERPOSTID
from
USERS
left join (
select
USERID
, row_number() over (
partition by USERID
order by LAST_EDIT_TIME desc) row_num
from
USERPOST
) most_recent
on most_recent.USERID = USERS.USERID
and row_num = 1