Mysql 删除语句有限制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7142097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 20:54:09  来源:igfitidea点击:

Mysql delete statement with limit

mysqlsql-order-bylimitsql-delete

提问by SBSTP

I'm trying to delete rows from a table but I get an error.

我正在尝试从表中删除行,但出现错误。

DELETE FROM `chat_messages` ORDER BY `timestamp` DESC LIMIT 20, 50;

I get this error at 50:

我在 50 时收到此错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' 50' at line 1

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在第 1 行的“50”附近使用的正确语法

No idea what's wrong.

不知道出了什么问题。

回答by zerkms

You cannot specify offset in DELETE's LIMITclause.

您不能在DELETE'sLIMIT子句中指定偏移量。

So the only way to do that is to rewrite your query to something like:

因此,唯一的方法是将您的查询重写为:

DELETE FROM `chat_messages` WHERE id IN (select id from (select id
                                           FROM `chat_messages`
                                       ORDER BY `timestamp` DESC
                                          LIMIT 20, 50) x)

Supposing that you have primary key idcolumn

假设你有主键id

UPD: you need to implement double nesting to fool mysql, since it doesn't allow to select from currently modified table (thanks to Martin Smith)

UPD:您需要实现双重嵌套来欺骗 mysql,因为它不允许从当前修改的表中进行选择(感谢 Martin Smith)