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

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

https://stackoverflow.com/questions/4268416/

相关文章:

mysql - ON UPDATE RESTRICT 有什么作用?

java - 使用 Java 通过 SSH 连接到远程 MySQL 数据库

sql - BIGINT(8) 是 MySQL 可以存储的最大整数吗?

mysql - 如何同步开发和生产数据库

mysql - 如何在 MySQL 的命令行中显示变量的值?

mysql - 获取 "Count(*)"与 "GROUP BY"中所有项目数的百分比

mysql - 如何让 MySQL 数据库完全在内存中运行?

php - 将大量点击记录到 MySQL 数据库中的最佳实践

mysql - org.hibernate.AssertionFailure : null id i

mysql - 查询以确定数据库中表的大小? (mysql)