簡體   English   中英

sqlite 通過多於兩行刪除行組

[英]sqlite delete rows group by having more than two rows

我有以下表結構:

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
                      );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM