我知道这听起来很混乱,但我不知道如何更好地解释它。我在下面简化了一个表格:
DB Type ID
================
Table1 1
Table1 2
Table1 3
Table1 4
Table1 5
Table2 6
Table2 7
Table2 8
Table2 9
Table2 10
我想要实现的是基本上清理掉这个表但是如果有意义的话,保留每个数据库类型的最高ID的记录 - 所以在这种情况下它将是(表1,5)和(表2,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
答案 0 :(得分:3)
首先选择最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;
答案 1 :(得分:1)
delete your_table
from
your_table left join
(select max(id) max_id from your_table group by type) mx
on your_table.id=mx.max_id
where mx.max_id is null
子查询返回每种类型的最大ID,这些是要保留的值。使用左连接,我选择表中没有in_ max_ids的所有行,这些是要删除的行。这只有在id是主键时才有效,否则我们也必须加入类型。
答案 2 :(得分:1)
组合数据库类型 - ID是唯一的吗?
如果是这样,你可以分两个阶段攻击它:
只获取您想要的行
SELECT [DB Type], Max(ID) AS MaxID
FROM YourTable
GROUP BY [DB Type]
删除其余部分(将前一个语句包含在更复杂的语句中;不代表)
DELETE FROM YourTable
FROM
YourTable
LEFT JOIN
(SELECT [DB Type], Max(ID) AS MaxID
FROM YourTable GROUP BY [DB Type]) DontDelete
ON
YourTable.[DB Type]=DontDelete.[DB Type] AND
YourTable.ID=DontDelete.MaxID
WHERE
DontDelete.[DB Type] IS NULL
答案 3 :(得分:0)
DELETE FROM MyTable del
WHERE EXISTS (
(SELECT *
FROM MyTable xx
WHERE xx."db Type" = del."db Type"
AND xx.id > del.id
);
答案 4 :(得分:0)
delete from my_Table
where Day in (select MAX(day) d from my_Table where id='id')