Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL UPDATE with sub-query that references the same table in MySQL

I'm trying to update a column's value in a bunch of rows in a table using UPDATE. The problem is that I need to use a sub-query to derive the value for this column, and it depends on the same table. Here's the query:

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

Ordinarily if teacher and student were in 2 different tables, mysql wouldn't complain. But since they are both using the same table, mysql spews out this error instead:

ERROR 1093 (HY000): You can't specify target table 'student' for update in FROM clause

Is there any way I can force mysql to do the update? I am 100% positive the from clause will not be affected as the rows are updated.

If not, is there another way I can write this update sql to achieve the same affect?

Thanks!

EDIT: I think I got it to work:

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'; 
like image 469
egervari Avatar asked Nov 24 '10 15:11

egervari


People also ask

Can I do a sub query in an UPDATE statement?

UPDATE operations with subqueries that reference the same table object are supported only if all of the following conditions are true: The subquery either returns a single row, or else has no correlated column references. The subquery is in the UPDATE statement WHERE clause, using Condition with Subquery syntax.

How UPDATE same column with different values in MySQL?

MySQL UPDATE multiple columnsMySQL UPDATE command can be used to update multiple columns by specifying a comma separated list of column_name = new_value. Where column_name is the name of the column to be updated and new_value is the new value with which the column will be updated.


2 Answers

Some reference for you 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 
like image 197
John Hartsock Avatar answered Oct 12 '22 01:10

John Hartsock


Abstract example with clearer table and column names:

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

As suggested by @Nico

Hope this help someone.

like image 37
Simon Arnold Avatar answered Oct 12 '22 01:10

Simon Arnold