我正在尝试使用 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';
通常如果教师和学生在 2 个不同的表中,mysql 不会抱怨。但由于它们都使用同一个表,mysql 会喷出这个错误:
ERROR 1093 (HY000): 您不能在 FROM 子句中指定目标表 'student' 进行更新
有什么办法可以强制mysql进行更新吗?我 100% 肯定 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';