mysql - 带有引用 MySQL 中同一个表的子查询的 SQL UPDATE

标签 mysql sql mysql-error-1093

我正在尝试使用 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/

相关文章:

mysql - 删除双倍用户(MySQL)

mysql - 在 MySQL 上创建类型

mysql - 当第三个表中可能不存在值时从 3 个表中进行选择

sql - 来自 foreign_key 列的带有字符串前缀的递增序列

MySQL INSERT 在同一张表上使用带 COUNT() 的子查询

mysql - 相关子查询更新

python - 使用 Flask/SQLAlchemy 最后对零进行排序

php - 从数据库获取流行词("trending"短语)

mysql - mysql 5.6插入语句中的自动增量漏洞

mysql - 删除sql约束