Problem joining tables where joined table needs to be ordered before grouping

走远了吗. 提交于 2019-12-01 08:07:50

问题


I have a scenario, which is seemingly simple on paper, but I'm having trouble getting to work as desired in practice.

I have two tables (only relevant columns presented):

| Thread
+----------
| ThreadID 

| Post
+----------
| PostID
| ThreadID
| Posted (Datetime)

Now, what I want to do, is to join Thread and Post, grouping by ThreadID. But I want to order by Post.Posted in descending order. In plain english, I want to join Thread on the most recent Post relating to it.

My SQL so far:

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 

It does the job, but the order of the join is not correct, as the ordering is, of course, applied only after the grouping is performed.

Surely, there must be a way to accomplish what I need?


回答1:


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



回答2:


Use both the thread id and the created date in the order by clause

SELECT Thread.ThreadID, Post.PostID, Post.Created
FROM Thread
LEFT JOIN Post ON Post.ThreadID = Thread.ThreadID
GROUP BY Thread.ThreadID
ORDER BY Thread.ThreadID, Post.Created DESC 


来源:https://stackoverflow.com/questions/2341659/problem-joining-tables-where-joined-table-needs-to-be-ordered-before-grouping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!