[英]SQL UPDATE with sub-query that references the same table in 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所建議的那樣
希望這能有所幫助。
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';
我需要這個用於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
我認為它適用於其他RDBMS(請確認)。 我喜歡語法,因為它是可擴展的。
我需要的格式實際上是:
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';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.