ACTUALIZACIÓN SQL con sub-consulta que hace referencia a la misma tabla en MySQL


Estoy tratando de actualizar el valor de una columna en un montón de filas en una tabla usando UPDATE. El problema es que necesito usar una sub-consulta para derivar el valor de esta columna, y depende de la misma tabla. Aquí está la consulta:

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

Normalmente si el profesor y el estudiante estuvieran en 2 tablas diferentes, mysql no se quejaría. Pero como ambos están usando la misma tabla, mysql arroja este error en su lugar:

ERROR 1093 (HY000): No se puede especificar la tabla de destino 'estudiante' para actualización de la cláusula

¿Hay alguna manera de forzar a mysql a hacer la actualización? Estoy 100% seguro de que la cláusula from no se verá afectada a medida que se actualicen las filas.

Si no, ¿hay otra forma de escribir esta actualización sql para lograr el mismo efecto?

Gracias!

EDITAR: Creo que lo conseguí para trabajar:

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';
Author: OMG Ponies, 2010-11-24

7 answers

Alguna referencia para ti 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
 44
Author: John Hartsock,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-24 15:31:38

Ejemplo abstracto con nombres más claros de tabla y columna:

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

Como sugiere @Nico

Espero que esto ayude a alguien.

 20
Author: Simon Arnold,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-13 18:26:59
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'

Arriba están las consultas de actualización de ejemplo...

Puede escribir una consulta secundaria con la instrucción update SQL, no necesita dar un nombre de alias para esa tabla. dar nombre de alias a la tabla de sub consulta. Lo intenté y está funcionando bien para mí....

 5
Author: Ricky Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-10 22:05:11
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
Author: Sin2,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-07 16:13:17

Necesitaba esto para SQL Server. Aquí está:

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

Creo que funciona con otros RDBMSes (por favor confirme). Me gusta la sintaxis porque es extensible.

El formato que necesitaba era este:

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
 2
Author: Mahmoodvcs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-23 17:26:25

Obtengo "Error: Uso no válido de la función de grupo" cuando hago eso.

Pero este post: consulta mysql para actualizar el campo a max (campo) + 1

Muestra una cosa de subselección aún más anidada, que funciona.

 1
Author: Gayle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:55:00
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';
 -3
Author: Magizh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-07 17:04:25