40

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';
4

7 に答える 7

44

あなたのための参考文献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
于 2010-11-24T15:24:50.517 に答える
20

より明確なテーブル名と列名を使用した抽象的な例:

UPDATE tableName t1
INNER JOIN tableName t2 ON t2.ref_column = t1.ref_column
SET t1.column_to_update = t2.column_desired_value

@Nicoが示唆するように

これが誰かを助けることを願っています。

于 2014-05-21T01:21:42.720 に答える
2
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';
于 2013-06-07T15:54:50.253 に答える
2

これは 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
于 2015-02-23T17:26:25.500 に答える
-3
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';
于 2012-06-07T11:56:01.590 に答える