我正在尝试使用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会发出此错误:
错误1093(HY000):您无法在FROM子句中指定目标表“学生”进行更新
有什么办法可以强制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';
为您提供一些参考http://dev.mysql.com/doc/refman/5.0/en/update.html
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