在stackoverflow(https://stackoverflow.com/a/578926/3152204)中查看这个答案,我很想知道如何在sqlalchemy中执行此查询。
DELETE FROM `table`
WHERE id NOT IN (
SELECT id
FROM (
SELECT id
FROM `table`
ORDER BY id DESC
LIMIT 42 -- keep this many records
) foo
);
答案 0 :(得分:0)
这是一种方法。
from sqlalchemy.sql import select
#no need to keep the whole table here
ids_to_keep = select([table.c.id, table.c.timestamp]).order_by(table.c.timestamp.desc()).limit(42)
#execute the final query
connection.execute(table.delete().where(table.c.id != ids_to_keep.c.id)).fetchall()