我正在使用SQLite 3.11。我按如下方式创建了一个表:
CREATE TABLE MyTable (F1 INTEGER, F2 INTEGER, F3 INTEGER);
然后添加以下记录:
INSERT INTO MyTable (F1, F2, F3) Values (1, 2, 8);
INSERT INTO MyTable (F1, F2, F3) Values (1, 3, 9);
INSERT INTO MyTable (F1, F2, F3) Values (2, 4, 8);
INSERT INTO MyTable (F1, F2, F3) Values (2, 5, 2);
INSERT INTO MyTable (F1, F2, F3) Values (3, 6, 4);
INSERT INTO MyTable (F1, F2, F3) Values (3, 7, 8);
INSERT INTO MyTable (F1, F2, F3) Values (3, 7, 9);
INSERT INTO MyTable (F1, F2, F3) Values (4, 2, 4);
INSERT INTO MyTable (F1, F2, F3) Values (4, 2, 6);
现在我想消除重复记录,因此对于两个F1和F2值相同的记录,即使它们的F3值不同,也会保留一个最大值为F3的记录,另一个记录将被删除。
使用DELETE语句可以吗?
由于
答案 0 :(得分:0)
首先,构建一个查找要删除的所有记录的查询:
SELECT *
FROM MyTable
WHERE F3 < (SELECT MAX(F3)
FROM MyTable AS T2
WHERE T2.F1 = MyTable.F1
AND T2.F2 = MyTable.F2);
然后使用表格的唯一字段(在本例中为内部rowid)来删除它们:
DELETE FROM MyTable
WHERE rowid IN (SELECT rowid
FROM MyTable
WHERE F3 < (SELECT MAX(F3)
FROM MyTable AS T2
WHERE T2.F1 = MyTable.F1
AND T2.F2 = MyTable.F2));