我有2个表,Posts
和Replies
。它们都包含PostID
,以及插入数据时的TimeStamp
。
在单个查询中,我想知道两个表中的最新条目以及该条目的关联PostID
。
我知道在MSSQL中我可以使用子查询来完成此操作,如下所示;
SELECT
PostID,
MAX(TimeStamp) as newTimeStamp
FROM (
SELECT
PostID as PostID
,TimeStamp as TimeStamp
FROM
Posts
UNION ALL
SELECT
PostID as PostID
,TimeStamp as TimeStamp
FROM
Replies
)
GROUP BY
PostID
ORDER BY
newTimeStamp DESC
我现在已经20分钟了 - 我知道这是一个简单的解决方案。
为了澄清,PostID
是Posts
的PK,PostID
是Replies
的FK。我想知道,所有PostID
上的最新活动,按TimeStamp降序排列
答案 0 :(得分:1)
这个怎么样?
SELECT
, Posts.PostID
, Posts.TimeStamp as LatestPost
, Replies.TimeStamp as LatestReply
, COALESCE(Replies.TimeStamp, Posts.TimeStamp) as LastActivity
FROM
Posts
LEFT OUTER JOIN
Replies
ON
Replies.PostID = Posts.PostID
WHERE
Posts.TimeStamp =
(SELECT MAX(TimeStamp)
From Posts sub
WHERE sub.PostID = Posts.PostID )
AND
(Replies.TimeStamp is NULL
OR Replies.TimeStamp =
(SELECT MAX(TimeStamp)
FROM Replies sub
WHERE sub.PostID = Posts.PostID
)
)
ORDER BY 4 DESC