子查询再多套一层(不过这样就不支持走索引了,线上环境慎用!)
不支持的写法:
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
本站文章除注明转载/出处外,均为原创,若要转载请务必注明出处。转载后请将转载链接通过邮件告知我站,谢谢合作。本站邮箱:admin@only4.work
尊重他人劳动成果,共创和谐网络环境。点击版权声明查看本站相关条款。