首页 > 解决方案 > 如何在按组和日期排序后删除除一行之外的所有 MySQL 行?

问题描述

我有这张桌子

在此处输入图像描述

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

在此处输入图像描述

标签: mysqlsql

解决方案


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

推荐阅读