Postgresql

查找所有 ID 都小於某個日期的 ID

  • October 14, 2019

考慮一個帶有 id-datetime 欄位的簡單表。我想刪除日期時間小於某個常數的所有記錄,但保留至少有一條日期較大的記錄的 ID。

我的第一個努力是

DELETE FROM journal
WHERE id IN (
 SELECT
       j.id
 FROM
       journal j
 WHERE NOT EXIST (SELECT * FROM journal j2 
                  WHERE j.id == j2.id AND j2.created_at >= 636742944000000000
)

效果不佳。然後我重寫如下

DELETE FROM journal
WHERE id IN (
 SELECT
       j.id
 FROM
       journal j
 GROUP BY id
 HAVING MAX(created_at) < 636742944000000000;
)

哪個表現得更好。

但我仍然想知道最高效的方法是什麼?也許一些特定於供應商的查詢擴展?

請試試這個:

DELETE FROM journal
WHERE id NOT IN (
 SELECT
       j.id
 FROM
       journal j
 WHERE j.created_at >= 636742944000000000
 ORDER BY j.created_at DESC
)

請確保在created_at和上創建索引id

另外,我認為id表格中應該是unique/ primary key

我認為你已經在做最好的方式。

DELETE FROM journal
WHERE id NOT in 
 (SELECT id 
   FROM journal
   GROUP BY (id)
   HAVING MAX(created_at) >= 636742944000000000);

引用自:https://dba.stackexchange.com/questions/249060