[英]SQL Server: select based on the latest id in a many to n:m relationship
我需要做的是选择评论详细信息以及对该评论采取的最后一项操作; 我有3张桌子:
评论
CommentID, commentText, userID, date_posted
行动
ActionID, action_taken,userID,date_actioned
和CommentJoinAction
id,ActionID,CommentID
可能有一个评论,但评论上有许多动作。
我的SQL看起来像:
Select /*snip comment details and such*/
From Comment
Inner Join (select max(actionid) from commentjoinaction) as cja on /*blah cause you know from reading this, it won't work*/
那么我能做些什么,以便我总是拿起最新的commentAction作为评论。
非常感谢
SELECT t.commentText, t.action_taken
FROM (SELECT c.commentText, a.action_taken,
ROW_NUMBER() OVER (PARTITION BY c.CommentID ORDER BY a.date_actioned DESC) AS RowNum
FROM Comment c
INNER JOIN CommentJoinAction cja
ON c.CommentID = cja.CommentID
INNER JOIN Action a
ON cja.ActionID = a.ActionID
) t
WHERE t.RowNum = 1
这是你想要的?
SELECT
/*Select desired fields*/
FROM Comments AS C
INNER JOIN (
SELECT
CommentID
,MAX(ActionID) AS ActionID
FROM CommentJoinAction
GROUP BY CommentID
)AS CJA
ON C.CommentID = CJA.CommentID
INNER JOIN ACTION AS A
ON CJA.ActionID = A.ActionID
select C.*, A.* from Comment C
inner join
(
select CommentID, Max(ActionID) as LatestActionID from CommentJoinAction
group by CommentID
) CJA on C.CommentID = CJA.CommentID
inner join Action A on CJA.LatestActionID = A.ActionID
如果您只想要actionID
select c.*, (
select max(actionID)
from CommentJoinAction cja
where cja.commentID = c.commentID
) as maxActionID
from Comment c
或者,如果您需要所有“操作”字段:
select c.*, a.*
from Comment c
inner join Action a
on a.actionID = (
select max(actionID)
from CommentJoinAction
where commentID = c.commentID
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.