Mysql删除顺序依次

时间:2012-09-12 06:21:20

标签: mysql sql

我有一张桌子,我只按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

我做错了什么?

5 个答案:

答案 0 :(得分:16)

试试这个,

DELETE FROM table
WHERE ID IN
        (
        SELECT ID
        FROM
            (
                SELECT ID
                FROM table
                WHERE Type = 'TEST'
                ORDER BY ID
                LIMIT 30,60
            ) a
        )

答案 1 :(得分:9)

第二次编辑:虽然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)

答案 2 :(得分:0)

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

DELETE FROM table
WHERE type = 'test'
AND ID IN (SELECT id from table where type = 'test' order by id desc limit 30 )

答案 3 :(得分:0)

试试这个

DELETE FROM table WHERE id in(SELECT id FROM table WHERE type = "test" order by id desc limit 30, 60)

答案 4 :(得分:0)

我无法在子查询中使用limit子句,因此我使用的解决方案有点凌乱: -

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)