SQL UPDATE引用MySQL中的同一个表的子查询
我试图用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子句中指定目标表'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
具有更清晰的表名和列名的抽象示例:
UPDATE tableName t1 INNER JOIN tableName t2 ON t2.ref_column = t1.ref_column SET t1.column_to_update = t2.column_desired_value
正如@Nico所build议的那样
希望这可以帮助别人。
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'
以上是示例更新查询…
您可以使用更新SQL语句编写子查询,您不需要为该表提供别名。 给子查询表提供别名。 我试过了,对我来说工作很好….
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';
当我这样做时,我得到“错误:组function的无效使用”。
但是这个post: mysql查询更新字段为max(field)+ 1
显示了一个更加嵌套的子查询事物。
我需要这个SQL Server。 这里是:
UPDATE user_account SET student_education_facility_id = cnt.education_facility_id from ( SELECT user_account_id,education_facility_id FROM user_account WHERE user_type = 'ROLE_TEACHER' ) as cnt WHERE user_account.user_type = 'ROLE_STUDENT' and cnt.user_account_id = user_account.teacher_id
我认为它适用于其他关系数据库(请确认)。 我喜欢这个语法,因为它是可扩展的。
我需要的格式实际上是这样的:
UPDATE table1 SET f1 = cnt.computed_column from ( SELECT id,computed_column --can be any complex subquery FROM table1 ) as cnt WHERE cnt.id = table1.id
UPDATE user_account student, ( SELECT teacher.education_facility_id as teacherid FROM user_account teacher WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER' ) teach SET student.student_education_facility_id= teach.teacherid WHERE student.user_type = 'ROLE_STUDENT';