让我们编写一个查询,返回用户名和组名的最新时间。
SELECT
UserName, GroupName, MAX(deprovision_time)
FROM
user_deprovision
GROUP BY
UserName, GroupName
现在,让我们根据您的目的进行调整。在 Oracle 中,我可能会做一些事情将其转换为临时表,但我将在此处使用相关子查询。
DELETE FROM user_deprovision AS dp1
WHERE dp1.deprovision_time <
ANY (SELECT deprovision_time FROM user_deprovision AS dp2
WHERE dp1.UserName = dp2.UserName
AND dp1.GroupName = dp2.GroupName);
我们可以把它变成一个连接。
SELECT dp1.id
FROM user_deprovision AS dp1
JOIN user_deprovision AS dp2
ON dp1.UserName = dp2.UserName
AND dp1.GroupName = dp2.GroupName
WHERE
dp1.deprovision_time < dp2.deprovision_time
而对应的删除是:
DELETE FROM user_deprovision
WHERE id IN (
SELECT dp1.id
FROM user_deprovision AS dp1
JOIN user_deprovision AS dp2
ON dp1.UserName = dp2.UserName
AND dp1.GroupName = dp2.GroupName
WHERE
dp1.deprovision_time < dp2.deprovision_time);