我有一个包含4列的表格:
ID,GUID,Binary,Timestamp。
我的目标是将二进制文件的最后10个修改保存到数据库中。如果插入了第11个修改,则应删除最旧的修改。
我目前的方法是分两步完成(伪mssql):
1) DELETE FROM mytable WHERE GUID = 'XXX' AND
ID NOT IN (SELECT TOP 9 ID FROM mytable WHERE GUID = 'XXX' ORDER BY Timestamp)
2) INSERT new binary ...
有没有办法更有效率,也许有一个声明?有没有办法使它兼容,mssql和postgresql兼容(没有TOP / Limit)?
答案 0 :(得分:3)
您可以使用cte来兼容:
with cte as (
select
row_number() over(order by Timestamp desc) as row_num
from mytable
where GUID = 'XXX'
)
delete from cte
where row_num > 10
编辑
请参阅Gordon Linoff的回答,我的语法在PostgreSQL中无效,只是在sqlfiddle中测试过。我在SQL Server上工作太多了......
<强> EDIT2 强>
关于在一个查询中删除和插入,PostgreSQL允许:
with cte_del as (
select
id,
row_number() over(order by id desc) as row_num
from tbl
where GUID = 'XXX'
), cte_d as (
delete from tbl where id in (select id from cte_del where row_num > 10)
)
insert into ...
select id from cte_del where row_num <= 10;
答案 1 :(得分:2)
我认为以下内容适用于SQL Server和Postgres:
with todelete as (
select id, row_number() over (partition by GUID order by timestamp) as seqnum
from mytable
where GUID = 'xxx'
)
delete from mytable
where id in (select id from todelete where seqnum > 10);