欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

关于My Sql update语句不能用子查询的解决办法

程序员文章站 2022-10-18 20:27:34
在使用My Sql数据库语法操作update时,第一时间想到的是一下写法: 但是这个时候就会报错:You can't specify target table 'xxx' for update in FROM My Sql的update的一些特点 1、update 时,更新的表不能在set和wher ......

  在使用My Sql数据库语法操作update时,第一时间想到的是一下写法:

UPDATE purchase_request_detail SET convert_to_voucher_id=2, convert_to_voucher_type='inventory-voucher' 
WHERE detail_id IN (select detail_id from purchase_request_detail where request_id=1 and item_id=1) ;

  但是这个时候就会报错:You can't specify target table 'xxx' for update in FROM

 

  My Sql的update的一些特点

    1、update 时,更新的表不能在set和where中用于子查询;

    2、update 时,可以对多个表进行更新(Sql Server不行);

             如:update table_a A,table_b B set A.B_ID=B.ID ,B.A_ID=A.ID;  

    3、update 后面可以做任意的查询,这个作用等同于FROM;

 

  所以My Sql update是不允许使用子查询的,正确写法是:

UPDATE purchase_request_detail AS table_1 
INNER JOIN (select detail_id from purchase_request_detail where request_id=1 and item_id=1) 
AS table_2 SET convert_to_voucher_id=2, convert_to_voucher_type='inventory-voucher'  WHERE table_1.detail_id = table_2.detail_id;