开发者

Mysql update subquery specify target table

I'm having trouble with updating final_id by selecting the highest final_id already in table and adding +1.

The query below outputs the error: "You can't specify target table 'customer_orders' for update in FROM clause" and I sadly fail to see why..

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}', 
 开发者_如何学JAVA     payment_cardnopostfix = '{$postfix}', 
      payment_fraud_suspicious = '{$fraud}' 
  WHERE id = '{$order_id}'

I'm trying to set a unique increasing ID for finalized orders in my system.

I hope someone can tell me what I'm doing wrong!

Best regards


You can rewrite your query and use join

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}'


change the inner query to SELECT max(final_id) FROM customer_orders


Try this:

 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}'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜