分享

MySQL执行update时的[ERROR 1093]处理方法

 我心永恒lz 2017-09-19


  1. >update TEST_NOIDX  set CREATETIME=now() where ID in ( select a.ID from TEST_NOIDX a where a.VNAME='Aa');  
  2. ERROR 1093 (HY000): You can't specify target table 'TEST_NOIDX' for update in FROM clause  
  3.   
  4. >update TEST_NOIDX b set b.CREATETIME=now() where b.ID in ( select a.ID from TEST_NOIDX a where a.VNAME='Aa');  
  5. ERROR 1093 (HY000): You can't specify target table 'b' for update in FROM clause  


从oracle转mysql的同志们,估计都会遇到上面这种情况,怎么这样的sql执行不了。

为什么会这样?

字面意思就是update的表不能出现在from语句中,原因是mysql对子查询的支持是比较薄弱的 。

而且手册上面说下面的这些情况都会报错

[plain] view plain copy
  1. ·  In general, you cannot modify a table and select from the same table in a subquery. For example, this limitation applies to statements of the following forms:  
  2. DELETE FROM t WHERE ... (SELECT ... FROM t ...);  
  3. UPDATE t ... WHERE col = (SELECT ... FROM t ...);  
  4. {INSERT|REPLACE} INTO t (SELECT ... FROM t ...);  
  5. Exception: The preceding prohibition does not apply if you are using a subquery for the modified table in the FROM clause. Example:  
  6. UPDATE t ... WHERE col = (SELECT (SELECT ... FROM t...) AS _t ...);  


两种解决方法,

1.改成inner join,手册上的方法。

2.多加一个嵌套。


  1. >update TEST_NOIDX set CREATETIME = now() where ID in (select id from ( select id from TEST_NOIDX where VNAME ='Aa') aa);  
  2. Query OK, 2 rows affected (0.05 sec)  
  3. Rows matched: 2  Changed: 2  Warnings: 0  
  4.   
  5. >update TEST_NOIDX b  inner join  ( select a.ID,a.CREATETIME from TEST_NOIDX a where a.VNAME='Aa') c on b.ID=c.ID set b.CREATETIME=now();  
  6. Query OK, 2 rows affected (0.04 sec)  
  7. Rows matched: 2  Changed: 2  Warnings: 0  






    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多