postgresql 从postgres表中删除一些旧记录

jw5wzhpr  于 2023-08-04  发布在  PostgreSQL
关注(0)|答案(3)|浏览(175)

我有一张table:

table t1
id int
room text
record_date timestamp

字符串
如何删除t1表中的一些记录,除了房间的最新100条记录(record_date用于保存要比较的时间戳)?
使用mysql,我做了下一个,它工作:

DELETE  p FROM t1 p
            LEFT JOIN 
            (SELECT id,room
            FROM t1
            ORDER BY record_date DESC
            LIMIT 101) p2 on p2.id=p.id and p2.room=p.room 
            WHERE p2.id IS NULL and p.room='myroom'


但是postgres不能使用它,并且会导致错误。

ki0zmccv

ki0zmccv1#

请尝试以下操作:

DELETE FROM t1
WHERE (room, id) NOT IN (
    SELECT room, id
    FROM t1
    WHERE room = 'myroom'
    ORDER BY record_date DESC
    LIMIT 100
);

字符串

ee7vknir

ee7vknir2#

试试这个从this answer改编的:

WITH todelete AS (
   SELECT * FROM t1
   WHERE room = 'myroom'
   ORDER BY record_date DESC
   OFFSET 100 ROWS
 )
 DELETE FROM todelete;

字符串

e0bqpujr

e0bqpujr3#

您可以尝试以下命令:

DELETE FROM t1
WHERE room = 'myroom' AND NOT EXISTS 
(
   SELECT id
   FROM t1 p2
   WHERE p2.room = t1.room
   ORDER BY record_date DESC
   OFFSET 100
   LIMIT 1
);

字符串
使用“不存在”的原因将确保所选记录比房间中第100个最新记录更早。

相关问题