2017-09-22 51 views
-1

看着這個答案在stackoverflow(https://stackoverflow.com/a/578926/3152204),我很好奇,看看這個查詢如何在sqlalchemy執行。我將如何在SQL鍊金術中執行刪除子查詢?

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

這是一個奇怪的查詢,這個又是什麼的地步,'選擇ID FROM(SELECT ID FROM表 ORDER BY ID DESC LIMIT 42'。 –

+0

@aws_apprentice據我引用的答案,用戶的回答指出,如果沒有中間子查詢,就會出現兩個錯誤: – EndenDragon

+0

答案是從09開始,肯定有些改變了,沒有? –

回答

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() 
+0

這將編譯爲'DELETE FROM tbl WHERE tbl.id!= id',除非id是NaN,否則它將刪除恰好爲0的行。你打算做'ids_to_keep = select([table.c.id])。order_by(table.c.timestamp.desc())。limit(42)'然後'table.delete()。where(table.c .id.notin_(ids_to_keep))'。 –