MySQL, actualizar varias tablas con una consulta


Tengo una función que actualiza tres tablas, pero uso tres consultas para realizar esto. Deseo utilizar un enfoque más conveniente para las buenas prácticas.

¿Cómo puedo actualizar varias tablas en MySQL con una sola consulta?

Author: Ryan Kohn, 2010-12-06

6 answers

Puede hacer esto con un procedimiento almacenado combinando las instrucciones UPDATE en una sola transacción.

 -16
Author: Freddie,
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-01-17 20:08:17

Tomemos el caso de dos tablas, Books y Orders. En caso de que aumentemos el número de libros en un orden particular con Order.ID = 1002 en la tabla Orders, también necesitamos reducir el número total de libros disponibles en nuestro stock en el mismo número en la tabla Books.

UPDATE Books, Orders
SET Orders.Quantity=Orders.Quantity+2,
Books.InStock=Books.InStock-2
WHERE Books.BookID=Orders.BookID
 AND Orders.OrderID = 1002;
 384
Author: Irfan,
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
2014-08-07 04:16:44
UPDATE t1
INNER JOIN t2 ON t2.t1_id = t1.id
INNER JOIN t3 ON t2.t3_id = t3.id
SET t1.a = 'something',
    t2.b = 42,
    t3.c = t2.c
WHERE t1.a = 'blah';

Para ver qué se va a actualizar, puede convertir esto en una instrucción select, por ejemplo:

SELECT t2.t1_id, t2.t3_id, t1.a, t2.b, t2.c AS t2_c, t3.c AS t3_c
FROM t1
INNER JOIN t2 ON t2.t1_id = t1.id
INNER JOIN t3 ON t2.t3_id = t3.id
WHERE t1.a = 'blah';
 40
Author: Wodin,
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
2016-12-31 10:59:38

También puede hacer esto con una consulta también usando una combinación como esta:

UPDATE table1,table2 SET table1.col=a,table2.col2=b
WHERE items.id=month.id;

Y luego simplemente envíe esta consulta, por supuesto. Puedes leer más sobre joins aquí: http://dev.mysql.com/doc/refman/5.0/en/join.html. También hay un par de restricciones para ordenar y limitar las actualizaciones de varias tablas que puede leer aquí: http://dev.mysql.com/doc/refman/5.0/en/update.html (solo ctrl + f "unir").

 30
Author: Stephen Searles,
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-12-05 23:23:09

Cuando dice múltiples consultas, quiere decir múltiples sentencias SQL como en:

UPDATE table1 SET a=b WHERE c;
UPDATE table2 SET a=b WHERE d;
UPDATE table3 SET a=b WHERE e;

O múltiples llamadas a funciones de consulta como en:

mySqlQuery(UPDATE table1 SET a=b WHERE c;)
mySqlQuery(UPDATE table2 SET a=b WHERE d;)
mySqlQuery(UPDATE table3 SET a=b WHERE e;)

Lo primero se puede hacer usando una sola llamada mySqlQuery si eso es lo que quería lograr, simplemente llame a la función mySqlQuery de la siguiente manera:

mySqlQuery(UPDATE table1 SET a=b WHERE c; UPDATE table2 SET a=b WHERE d; UPDATE table3 SET a=b WHERE e;)

Esto ejecutará las tres consultas con una llamada a mySqlQuery ().

 1
Author: code_burgar,
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-12-05 23:05:42

Para eso suelen ser los procedimientos almacenados: implementar varias sentencias SQL en una secuencia. Al usar reversiones, puede asegurarse de que se traten como una unidad de trabajo, es decir, que se ejecuten todas o ninguna, para mantener la coherencia de los datos.

 0
Author: SteveCav,
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-12-05 22:56:39