[英]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.