问一个sql语句的问题


我的问题大致如下:

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

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

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

sql 数据库

jpshoo 10 years, 2 months ago

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的

圈圈老师的房管 answered 10 years, 2 months ago


 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

这货是杯具 answered 10 years, 2 months ago

Your Answer