简体   繁体   中英

SQLite Insert trigger how to delete old records in the table based on two values

I'm using SQLite Android, and I have a table that contains two columns id and feedId, I want to delete old items in the same feedId after insert new records if count > 10 This is the table

id  feedId
1   1
2   1
3   1
4   1
5   1
6   1
7   1
8   1
9   1
10  1
11  1
12  2
13  2
14  2
15  2
16  2
17  2
18  2
19  2
20  2
21  2
22  2

I have 11 records in the feedId 1 and 11 records in the feedId 2 so I want to delete 1 record from feedId 1 and 1 record from feedId 2

Tried this query

CREATE TRIGGER IF NOT EXISTS articles_limiter AFTER INSERT ON articles BEGIN DELETE FROM articles WHERE feedId in (SELECT feedId FROM (SELECT feedId,count(*) as cnt FROM articles GROUP BY feedId HAVING cnt > 10)) ORDER BY id DESC LIMIT -1 OFFSET 10; end;

But it's work only if there is one feedId that have count > 10, but it will not work if there is two or more feedId that have count > 10

If you want 10 rows per feedId , use row_number() :

select a.*
from (select a.*, row_number() over (partition by feedId order by id desc) as seqnum
      from articles a
     ) a
where seqnum <= 10;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM