sqlite 通过超过两行来删除行组

sqlite delete rows group by having more than two rows

我有以下 table 结构:

sqlite> select * from test;      
k1          k2          value     
----------  ----------  ----------
1           1           10        
1           1           20
1           1           30        
1           2           10

在这里,我想删除在 (k1,k2) 上分组的超过两行的行。

所以,我想删除前三行 (1,1,10)、(1,1,20) 和 (1,1,30)。

我试过以下方法:

delete from test where rowid in (select test.rowid from test group by k1,k2 having count(*) > 2);

但是,子查询只给出最后一个 rowid :

sqlite> select test.rowid from test group by k1,k2 having count(*) > 2;
rowid     
----------
3

因此,所有三行都没有被删除。 而且,我不能在删除查询中直接使用 group by。

知道如何通过查询实现吗?

您可以使用 exists:

delete from test
    where exists (select 1
                  from test t2
                  where t2.k1 = test.k1 and t2.k2 = test.k2
                  group by t2.k1, t2.k2
                  having count(*) > 2
                 );

或对元组使用 in

delete from test
    where (k1, k2) in (select t2.k1, t2.k2
                       from test t2
                       group by t2.k1, t2.k2
                       having count(*) > 2
                      );