我尝试使用UPDATE语句更新表中一堆行的某个列的值。问题在于,我需要使用子查询来推导该列的值,而这个子查询依赖于相同的表格。以下是查询语句:
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';
通常情况下,如果老师和学生在两个不同的表中,mysql 就不会抱怨。但是由于它们都使用同一张表,因此 mysql 会报出以下错误:
ERROR 1093 (HY000):您无法在 FROM 子句中指定目标表 'student' 进行更新
有没有办法强迫 mysql 进行更新?我可以百分之百确定 from 子句不会受到影响,因为行将被更新。
如果不能,是否有其他方法可以编写这个更新 SQL 以实现相同的效果?
谢谢!
编辑:我想我已经让它工作了:
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';