You can't specify target table 'ship_product_cat' for update in FROM clause

有时候我们在编辑update时需要select作为条件,在mysql中有时会出现这样的错误:You can't specify target table for update in FROM clause错误的意思是说,不能先select出同一表中的某些值,再update这个表(在同一语句中)。

例如下面这个sql:

UPDATE ship_product_cat SET is_parent = 0  WHERE id in(
SELECT id FROM ship_product_cat WHERE name in('Control','Propeller/Shaft')
);

错误信息:

[SQL]UPDATE ship_product_cat SET is_parent = 0 WHERE id in(
SELECT id FROM ship_product_cat WHERE name in('Control','Propeller/Shaft'));
[Err] 1093 - You can't specify target table 'ship_product_cat' for update in FROM clause

 解决方法——换成下面的SQL就可以了 

UPDATE ship_product_cat SET is_parent =0WHERE id in(
SELECT
a.id FROM (SELECT id FROM ship_product_cat WHERE name in('Control','Propeller/Shaft'))a );

 

也就是说将select出的结果再通过中间表select一遍,这样就规避了错误。

 注意:这个错误会出现在mysql中,但不会出现在oracle中。

posted @ 2016-06-29 13:14  Tom1997  阅读(705)  评论(0编辑  收藏  举报