【问题标题】:sqlite delete rows group by having more than two rowssqlite 通过多于两行删除行组
【发布时间】:2021-05-30 09:54:24
【问题描述】:

我具有以下表结构:

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

下面,我想(K1,K2),其具有多于两行上分组删除行。 P>

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

我尝试以下:

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

因此,所有三行没有得到删除。 而且,我无法直接在删除查询使用组通过。 P>

上任何想法,它如何可通过查询实现? P>

【问题讨论】:

    标签: sql sqlite group-by sql-delete having-clause


    【解决方案1】:

    你可以使用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
                          );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多