0

我有一个有 4 列的表:

ID、GUID、二进制、时间戳。

我的目标是将二进制文件的最后 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)?

4

2 回答 2

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;

sql 小提琴演示

于 2013-08-19T13:51:23.460 回答
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);
于 2013-08-19T13:52:20.653 回答