Mysql更新子查询指定目标表

时间:2011-03-31 15:04:33

标签: mysql mysql-error-1093

我无法通过选择表格中最高的final_id并添加+1来更新final_id。

下面的查询输出错误:“您无法在FROM子句中为更新指定目标表'customer_orders'”,我遗憾地看不出原因..

UPDATE customer_orders 
  SET final_id = (SELECT final_id FROM customer_orders ORDER BY final_id DESC)+1, 
      status = 2, 
      payment_id = '{$transaction_id}', 
      payment_type = '{$type}', 
      payment_reserved = '{$amount}', 
      payment_currency = '{$cur}', 
      payment_cardnopostfix = '{$postfix}', 
      payment_fraud_suspicious = '{$fraud}' 
  WHERE id = '{$order_id}'

我正在尝试为我的系统中的最终订单设置一个唯一的增加ID。

我希望有人可以告诉我我做错了什么!

祝你好运

3 个答案:

答案 0 :(得分:1)

您可以重写查询并使用加入

UPDATE customer_orders 
INNER JOIN (SELECT IFNULL(MAX(final_id),0) as max_id FROM customer_orders)a ON(1=1)
SET final_id = a.max_id+1, status = 2, payment_id = '{$transaction_id}', 
payment_type = '{$type}', payment_reserved = '{$amount}', 
payment_currency = '{$cur}', payment_cardnopostfix = '{$postfix}',
payment_fraud_suspicious = '{$fraud}' 
WHERE id = '{$order_id}'

答案 1 :(得分:0)

将内部查询更改为SELECT max(final_id) FROM customer_orders

答案 2 :(得分:0)

试试这个:

 UPDATE customer_orders        
    SET final_id = MT.MaxId + 1           -- use the computed max id, and increment
      , status = 2
      , payment_id = '{$transaction_id}'
      , payment_type = '{$type}'
      , payment_reserved = '{$amount}'
      , payment_currency = '{$cur}'
      , payment_cardnopostfix = '{$postfix}'
      , payment_fraud_suspicious = '{$fraud}'
   FROM customer_orders
      -- include a subquery to determine the max id from the customer_orders table
      -- and assign 'MT' as the name of the results table
      , (SELECT MAX(final_id) as MaxId FROM customer_orders) MT
  WHERE id = '{$order_id}'