问一个sql语句的问题

我的问题大致如下:

一张表tableA专门记录用户发布的内容,有多个用户,每个用户有多条内容;pid是tableA表中的一个外键,用来唯一标识一个用户;

给定一个pid的列表pids,如何编写sql语句,从tableA中查找出pids中每个用户的最新发布的一条内容来?

求大神指教!!谢谢!!!

阅读 3.1k
2 个回答
select t2.* from 
(select pid from tableA group by pid) as t1 OUTER APPLY
(select top(1) * from tableA where pid = t1.pid order by created desc) as t2

select * from tableA as t left join ( select tableB.* from tableB as t1 inner join (select pid,max(create_at) as max_create_at from tableB group by pid) as t2 on t1.pid = t2.pid and t1.create_at = t2.max_create_at ) as t3 on t.pid = t3.pid where t.pid in (1,2,3);
大体是这样,这是Mysql的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题