18

我有一张桌子,我只按 ID 顺序显示最新的 30 行。

我正在尝试使用下面的查询删除 30 个最新行之后的所有行。

DELETE FROM table WHERE type = 'test' ORDER BY id DESC LIMIT 30, 60

我在下面不断收到此错误

#1064 - 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 ' 60' at line 1

我究竟做错了什么?

4

5 回答 5

27

试试这个,

DELETE FROM table
WHERE ID IN
        (
        SELECT ID
        FROM
            (
                SELECT ID
                FROM table
                WHERE Type = 'TEST'
                ORDER BY ID
                LIMIT 30,60
            ) a
        )
于 2012-09-12T06:25:13.327 回答
8

第二次编辑:虽然 MySQL 在删除语句中支持 LIMIT,但它不允许 OFFSET。这意味着您不能跳过前 30 行。

对 id (或任何其他主键)进行子选择:

DELETE FROM table WHERE id IN (SELECT id FROM table WHERE type = 'test' ORDER BY id DESC LIMIT 30, 60)
于 2012-09-12T06:23:33.550 回答
0

这是不可能的。您可以尝试使用嵌套的 select 语句,有点像这样:

DELETE FROM table
WHERE type = 'test'
AND ID IN (SELECT id from table where type = 'test' order by id desc limit 30 )
于 2012-09-12T06:26:01.007 回答
0

像这样试试

DELETE FROM table WHERE id in(SELECT id FROM table WHERE type = "test" order by id desc limit 30, 60)
于 2012-09-12T06:26:47.123 回答
0

我无法在子查询中使用限制子句,所以我使用的解决方案,有点混乱,是:-

select group_concat(id) into @idList from
( 
select id from  table order by id desc limit 0,30
) as saveIds;
delete from table where not find_in_set(id,@idList)

或者,

select group_concat(id) into @idList from
( 
select id from  table order by id desc limit 30
) as saveIds;
delete from table where find_in_set(id,@idList)
于 2017-09-04T09:50:05.423 回答