-1

我不明白如何优化我的子查询:

SELECT *
FROM rp_clientAffectationHistory as T1
WHERE rp_clientAffectationHistoryID in (SELECT MAX(rp_clientAffectationHistoryID)
        FROM rp_clientAffectationHistory as T2
GROUP BY `rp_clientID`)
AND `rp_userID` = 57

对于相同的“rp_clientID”,我有许多重复的条目;我只想要具有最新 rp_clientAffectationHistoryID 的记录。

4

3 回答 3

1

你需要的是这样的:

SELECT *
  FROM Rp_Clientaffectationhistory AS T1
left join Rp_Clientaffectationhistory as T2 on (T1.Rp_Clientid = T2.Rp_Clientid) and T1.Rp_Clientaffectationhistoryid < T2.Rp_Clientaffectationhistoryid
where T2.Rp_Clientaffectationhistoryid is null
and T1.Rp_Userid = 57

它有帮助吗?

于 2013-12-06T09:36:50.650 回答
0

我想您只想为每个条目获得一个条目rp_clientID-

您错过的一件事是检查rp_clientID内部查询 -

SELECT *
  FROM Rp_Clientaffectationhistory AS T1
 WHERE Rp_Clientaffectationhistoryid IN
       (SELECT MAX(Rp_Clientaffectationhistoryid)
          FROM Rp_Clientaffectationhistory AS T2
         WHERE T1.Rp_Clientid = T2.Rp_Clientid
         GROUP BY Rp_Clientid)
   AND Rp_Userid = 57

是你要找的吗?

于 2013-05-20T07:47:47.180 回答
0

对于 Sql 服务器,请尝试:

SELECT * FROM(
    SELECT *, ROW_NUMBER() over (partition by rp_userID order by rp_clientAffectationHistoryID desc) Rnum 
    FROM rp_clientAffectationHistory
    WHERE rp_userID = 57
)x
WHERE Rnum=1
于 2013-05-20T07:50:01.767 回答