我有一张有四列的桌子:
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)?

最佳答案

我认为以下内容在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);

关于sql - 最多允许10个具有相同GUID的项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18315435/

10-16 20:59