问题
I'm using cockroachdb. For each group (grouped by id field), if the number of records exceeds 1000, I want to delete the oldest however_many records so that the number of records equal 1000 after the deletion.
This is what I have so far:
(select id, count(*) - 1000 as num_delete
from db.table
group by id
having count(*) > 1000)
Which gives me the ids for which records will be deleted, as well as the number of records I'll need to delete.
id | num_delete
+-----------+------------+
n7ia6ryc | 437
Is there a way, using one sql statement, that I can add to the sql query above so that those records are deleted?
回答1:
I don't know if this works in CockroachDB. If you have a column that is unique, then you can do:
delete from t
where t.unique_col < (select t2.unique_col
from t t2
where t2.id = t.id
order by t2.unique_col
fetch first 1 row only offset 99 rows
);
This finds the 100s value of "unique_col" for each id
and then deletes all rows (with the same id
) that have a smaller value.
If there are not 100 values, then the subquery returns NULL
and nothing is deleted.
来源:https://stackoverflow.com/questions/57915714/sql-delete-oldest-n-records-from-each-group