[Err] 1093 - You can't specify target table 'a' for update in FROM clause (MYSQL报错)

版权声明:欢迎评论和转载,转载时请注明作者和出处,共同维护良好的版权和知识产权秩序。 https://blog.csdn.net/CrazyOnes/article/details/84133833

前几天需要对数据库表做一个略微复杂的更新操作,当时写的语句大概是这样:

update archives a, sys_user s 
set s.username = a.stu_name 
where s.id = a.id and a.phone IN (select a.phone
				    from archives a, sys_user s
				    where a.phone = s.mobile
				    GROUP BY a.phone
				    HAVING COUNT(*) > 1) 

需要利用一个表的数据更新另一个表的数据,但是同时更新的条件又是通过这两个表做联结查询得到的

逻辑是没有问题的

但是报错了:

[Err] 1093 - You can't specify target table 'a' for update in FROM clause

大概就是不能用某表的查询结果作为条件更新数据

网上资料说只有MySQL会出现这种问题

解决的方法也很简单

update archives a, sys_user s 
set s.username = a.stu_name 
where s.id = a.id and a.phone IN (select * from (select a.phone
						from archives a, sys_user s
						where a.phone = s.mobile
						GROUP BY a.phone
						HAVING COUNT(*) > 1) k) 

将查询结果重命名为一张表,然后再次select的结果就可以作为update的where条件了。

当然可能这个报错的原因不止这一种,后续如果有这个问题我会持续记录到这个文章中。


如有错误,欢迎指摘。也欢迎通过左上角的“向TA提问”按钮问我问题,我将竭力解答你的疑惑。

猜你喜欢

转载自blog.csdn.net/CrazyOnes/article/details/84133833