删除id最大的地方

时间:2011-07-01 16:51:41

标签: mysql

我想删除order_id最大的行,我试过这个:

DELETE FROM orders WHERE MAX(order_id)

但这是错的!还有其他想法吗?

感谢您的时间。

5 个答案:

答案 0 :(得分:9)

第一个想法(在许多其他完全相同的想法中):

DELETE FROM orders 
WHERE order_id = 
      ( SELECT MAX(order_id)
        FROM orders
      )

不幸的是MySQL抱怨:

> ERROR 1093 (HY000): You can't specify target table 'orders' for update in FROM
> clause

绕过错误的两种方法:

DELETE FROM orders 
WHERE order_id =
       ( SELECT maxo
         FROM  
           ( SELECT MAX(order_id) AS maxo
             FROM orders
           ) AS tmp
        )

或:

DELETE FROM orders
ORDER BY order_id DESC
LIMIT 1 

答案 1 :(得分:6)

对于MySQL,这将是最简单的:

DELETE FROM orders
ORDER BY order_id DESC
LIMIT 1;

你不能做其他几个人已经回答的子查询技巧,因为如果你从一个表中选择并在同一个查询中更新/删除它,MySQL就不喜欢它了。

答案 2 :(得分:3)

你可以尝试:

DELETE FROM orders where order_id = (select max(order_id) from orders)

答案 3 :(得分:0)

尝试子查询。

DELETE FROM orders WHERE order_id = (SELECT MAX(order_id) FROM orders)

答案 4 :(得分:-1)

尝试:

DELETE FROM orders where order_id = (SELECT MAX(order_id) FROM orders)