update 与select嵌套


1.用b表的结果为a表赋值

update student set hobby= (select hobby_name from hobby )

错误,提示“Subquery return more than one row"

update student set hobby= (select hobby_name from hobby limit 1)

执行ok

说明:查询结果应该是一个唯一字段才能给前面的a表字段赋值。

 

2.用一个表的查询结果给字段赋值

update student set hobby= (select hobby from student where studentid=1) where studentid=2

错误,提示You can't specify target table 'student' for update in FROM clause

解决办法:把查询结果作为临时表b,再次查询赋值

update student set hobby=

(select b.hobby from

(select hobby from student where studentid=1) as b

)

where studentid=2

执行ok

3.用同一个表的查询结果作为条件

update student set status =2 where studentid in( select studentid from student where studentid<10 and status=0 order by studentid asc limit 0,1)

错误,提示#1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

update student set status =2 where studentid in( select studentid from student where studentid<10 and status=0 order by studentid asc )

错误,提示You can't specify target table 'student' for update in FROM clause

解决办法:

改变查询方式,

 

update student set status =2 where studentid<10 and status=0 order by studentid asc limit 0,1
   或 把查询结果作为临时表b
update student a,( select studentid from student where studentid<10 and status=0 order by studentid asc limit 0,1) b set a.status =2 where a.studentid=b.studentid
 
或连接
update student a join ( select studentid from student where studentid<10 and status=0 order by studentid asc limit 0,1) b on a.studentid=b.studentid set a.status =2

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM