mysql 修改语句 子查询语句,带有子查询的SQL UPDATE,该子查询引用了MySQL中的同一张表...

博主尝试用UPDATE语句更新表中多行某列的值,需使用依赖同表的子查询,但MySQL报错不能在FROM子句中指定目标表更新。博主给出两种解决方案,一是用LEFT JOIN,二是用INNER JOIN来实现相同更新效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm trying to update a column's value in a bunch of rows in a table using UPDATE. The problem is that I need to use a sub-query to derive the value for this column, and it depends on the same table. Here's the query:

UPDATE user_account student

SET student.student_education_facility_id = (

SELECT teacher.education_facility_id

FROM user_account teacher

WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'

)

WHERE student.user_type = 'ROLE_STUDENT';

Ordinarily if teacher and student were in 2 different tables, mysql wouldn't complain. But since they are both using the same table, mysql spews out this error instead:

ERROR 1093 (HY000): You can't specify target table 'student' for update in FROM clause

Is there any way I can force mysql to do the update? I am 100% positive the from clause will not be affected as the rows are updated.

If not, is there another way I can write this update sql to achieve the same affect?

Thanks!

EDIT: I think I got it to work:

UPDATE user_account student

LEFT JOIN user_account teacher ON teacher.user_account_id = student.teacher_id

SET student.student_education_facility_id = teacher.education_facility_id

WHERE student.user_type = 'ROLE_STUDENT';

解决方案

UPDATE user_account student

INNER JOIN user_account teacher ON

teacher.user_account_id = student.teacher_id

AND teacher.user_type = 'ROLE_TEACHER'

SET student.student_education_facility_id = teacher.education_facility_id

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值