我有一个场景,在纸上看似很简单,但是我很难按实际需要进行工作。
我有两个表(仅显示了相关的列):
| Thread +---------- | ThreadID | Post +---------- | PostID | ThreadID | Posted (Datetime)
现在,我要执行的操作是加入Thread和Post,并按ThreadID分组。但是我想按Post.Order降序排列。用简单的英语来说,我想加入Thread相关的最新帖子。
到目前为止,我的SQL:
SELECT Thread.ThreadID, Post.PostID, Post.Created FROM Thread LEFT JOIN Post ON Post.ThreadID = Thread.ThreadID GROUP BY Thread.ThreadID ORDER BY Post.Created DESC
它可以完成工作,但是联接的顺序不正确,因为该顺序当然仅在执行分组后才应用。
当然,必须有一种方法可以满足我的需求?
select t.ThreadID, p.PostID, p.Posted from Thread t inner join ( select ThreadID, Max(Posted) as MaxPosted from Post group by ThreadID ) pm on t. ThreadID = pm.ThreadID inner join Post p on pm.ThreadID = p.ThreadID and pm.MaxPosted = p.Posted order by p.Posted desc