我正在尝试使用 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 反而会喷出这个错误:
错误 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';
最佳答案
给你一些引用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
关于mysql - 带有引用 MySQL 中同一个表的子查询的 SQL UPDATE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4268416/