SQL UPDATE与子查询引用MySQL中的同一个表

ege*_*ari 40 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';
Run Code Online (Sandbox Code Playgroud)

通常,如果老师和学生在两个不同的表中,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';
Run Code Online (Sandbox Code Playgroud)

Joh*_*ock 45

一些参考资料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
Run Code Online (Sandbox Code Playgroud)

  • 如果有两个解决方案会更好:特定的和一个更抽象的,更清晰的表和列名称,以简化阅读寻找一般答案的人,像我一样.在任何情况下,问题和答案都满足我,但我建议它更好地了解社区.谢谢,两者都是+1 (6认同)
  • 完全同意@Nico的观点.这就是为什么我提供了一个具有更清晰的表名和列名的抽象示例(http://stackoverflow.com/a/23772515/886539).我也赞成了John Hartsock的答案(帮助我创造了我的榜样). (2认同)

Sim*_*old 20

具有更清晰的表和列名称的抽象示例:

UPDATE tableName t1
INNER JOIN tableName t2 ON t2.ref_column = t1.ref_column
SET t1.column_to_update = t2.column_desired_value
Run Code Online (Sandbox Code Playgroud)

正如@Nico所建议的那样

希望这能有所帮助.


小智 5

UPDATE user_account 
SET (student_education_facility_id) = ( 
    SELECT teacher.education_facility_id
    FROM user_account teacher
    WHERE teacher.user_account_id = teacher_id
    AND teacher.user_type = 'ROLE_TEACHER'
)
WHERE user_type = 'ROLE_STUDENT'
Run Code Online (Sandbox Code Playgroud)

以上是示例更新查询...

您可以使用更新SQL语句编写子查询,您不需要为该表提供别名.为别查询表提供别名.我试过,它对我来说很好......