如何按组和日期排序后删除除一行以外的所有MySQL行?

时间:2018-05-27 12:20:50

标签: mysql sql

我有这张桌子

enter image description here

我想创建一个存储过程来删除所有记录,但只保留每个Application_Id和External_Account_Id的最新记录(具有最新的Last_Warning_Message)。所以在执行存储过程之后,表应该是这样的:

enter image description here

1 个答案:

答案 0 :(得分:1)

在MySQL中,您可以在join

中使用delete
delete t
    from thistable t join
         (select Application_Id, External_Account_Id, 
                 max(Last_Warning_Message) as max_Last_Warning_Message
          from thistable t
          group by Application_Id, External_Account_Id
         ) tt
         on t.Application_Id = tt.Application_Id and
            t.External_Account_Id = tt.External_Account_Id and
            t.Last_Warning_Message < tt.max_Last_Warning_Message;