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 に更新を強制する方法はありますか? 行が更新されても from 句が影響を受けないことは 100% 確信しています。
そうでない場合、この更新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';