【问题标题】:SQL Server: select based on the latest id in a many to n:m relationshipSQL Server:基于多对n:m关系中的最新ID进行选择
【发布时间】:2011-03-10 17:49:46
【问题描述】:

我需要做的是选择评论详情和对评论采取的最后行动;我有 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*/

那么我能做些什么来让我总是为 cmets 获取最新的 commentAction。

非常感谢

【问题讨论】:

    标签: sql sql-server sql-server-2005 select


    【解决方案1】:
    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
    

    【讨论】:

      【解决方案2】:

      这是你要找的吗?

      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
      

      【讨论】:

      • 完美运行,正是我想要的。我在路上,但只是没有设法完成它。非常感谢。
      【解决方案3】:
      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
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 2021-02-07
          • 2020-11-22
          • 1970-01-01
          • 2018-09-27
          • 2022-01-22
          • 1970-01-01
          • 1970-01-01
          • 2022-06-13
          • 1970-01-01
          相关资源
          最近更新 更多