我知道这听起来很混乱,但是我不知如何更好地解释它。我有一个简化的表,如下所示:
DB Type ID ================ Table1 1 Table1 2 Table1 3 Table1 4 Table1 5 Table2 6 Table2 7 Table2 8 Table2 9 Table2 10
我想要达到的目的是基本上清除该表,但如果有意义的话,请为每个数据库类型保留具有最高ID的记录- 因此,在这种情况下,所有表的类型分别为(Table1,5)和(Table2,10)其他记录被删除。是否可以通过MySQL专门执行此操作?
感谢Yogendra Singh的提示
DELETE FROM MyTable WHERE ID NOT IN (SELECT * FROM (SELECT MAX(ID) from MyTable GROUP BY DB Type) AS tb1 ) ORDER BY ID ASC
尝试首先选择最大ID组db_type,然后将其用作子查询not in。
ID
db_type
not in
DELETE FROM MyTable WHERE ID NOT IN (SELECT ID FROM (SELECT MAX(ID) AS ID from MyTable GROUP BY DB Type) AS tb1 )
编辑:
DELETE FROM MyTable HAVING MAX(ID) > ID;