2011-03-10 44 views
0

我需要做的是選擇評論詳細信息以及對評論採取的最後一項操作;我有3個表:SQL Server:根據多對多關係中的最新ID進行選擇

評論

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。

千恩萬謝

回答

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 
+0

完美的作品,正是我一直在尋找。我正在走上這條路,但沒有完成它。非常感謝。 – Jarede 2011-03-11 09:28:11

4
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 
0
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 
0

如果你只是想在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 
)