子查詢再多套一層(不過這樣就不支援走索引了,線上環境慎用!)
不支援的寫法:
DELETE FROM your_table WHERE id NOT IN (SELECT id FROM your_table ORDER BY created_at DESC LIMIT 100);
報錯:
1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
支援的寫法:【注意】這樣寫就不支援走索引了
DELETE FROM your_table WHERE id NOT IN (SELECT id FROM (SELECT id FROM your_table ORDER BY created_at DESC LIMIT 100) AS sub_table);
測試:
select * FROM site_info_report_history WHERE id NOT IN (SELECT id FROM site_info_report_history ORDER BY id DESC LIMIT 10000) ORDER BY id DESC; select * FROM site_info_report_history WHERE id NOT IN (SELECT id FROM (SELECT id FROM site_info_report_history ORDER BY id DESC LIMIT 10000) AS sub_table) ORDER BY id DESC;
我這裏的表太大了,直接查資料庫容易崩掉。爲了測試查詢快下面兩個SQL執行時最後加上了LIMIT 1
EXPLAIN看一下,可以看到rows等於資料庫記錄數,Backward index scan,說明沒有走索引,直接全表掃描了,所以線上慎用!
參考:https://blog.csdn.net/weixin_42871288/article/details/121748859