ORDER BY与DELETE无法正常工作

时间:2013-06-19 06:30:54

标签: mysql mysql-workbench

我编写了这个删除查询以从表中删除重复的条目,但是当我运行此查询时,它将保留旧行并删除最新的行。我想保留最新插入的行,并希望删除旧的行。我在删除查询中附加了ORDER BY子句但它不起作用。

DELETE t2
FROM   user_deprovision t1
JOIN   user_deprovision t2 ON (
    t2.UserName  = t1.UserName  AND
    t2.GroupName = t1.Groupname AND
    t2.id > t1.id)
ORDER BY t1.DeletedDate;

我怎样才能做到这一点。

1 个答案:

答案 0 :(得分:0)

让我们编写一个查询,返回用户名和组名的最新时间。

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);