我很遗憾在网上多次询问这个问题,但我不明白如何优化我的子查询:
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的记录。
非常感谢
答案 0 :(得分: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
有帮助吗?
答案 1 :(得分: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
是你在寻找什么?
答案 2 :(得分:0)
对于Sql server,请尝试:
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