如何在SQL Alchemy中执行删除子查询?

时间:2017-09-22 00:23:20

标签: python sqlalchemy flask-sqlalchemy

在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
);

1 个答案:

答案 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()