almacenar el resultado establece en la tabla temporal, variable o variables separadas dentro de un disparador

dba.stackexchange https://dba.stackexchange.com/questions/3479

  •  16-10-2019
  •  | 
  •  

Pregunta

Estoy en el proceso de creación de algunos factores desencadenantes para almacenar el promedio de la calificación de un producto determinado en la tabla de productos. También me han preguntado para almacenar el número total de las revisiones de los productos. Por lo tanto - que necesito para recuperar los valores de 2 en mi gatillo, y luego actualizar la tabla de destino apropiada.

¿Debo usar sentencias de selección separados

SET my_a = SELECT a FROM foo;
SET my_b = SELECT b FROM foo;

una sola instrucción para recuperar un conjunto de resultados como una variable (es esto posible?):

SET var = SELECT (a,b) FROM foo; 
UPDATE bar SET c=var.a,d=var.b;

o tal vez incluso almacenar el conjunto de resultados en una tabla temporal dentro del disparador (es que posible?)?

¿Fue útil?

Solución

The first method is the best because of the least overhead for the queries generated. In fact, in the MySQL Stored Procedure Language, you want as few declared variables as possible.

The second is not possible since the MySQL Stored Rrocedure Language does not have object support. A clumsy but workable UPDATE JOIN is possible if you...

  1. update the question with the CREATE TABLE statement for the product table
  2. show us the trigger defintion you have thus far

The third method is not possible because explicit DDL and DDL via Dynamic SQL are not allowed in MySQL Triggers.

You may have to create a regular table using either the MyISAM or MEMORY storage engine. Then, you can have the trigger compile your data to a table that actually exists. MyISAM is better because should a server go down, the compiled data thus far is on disk. MEMORY tables are faster to write to, but are gone on system restart.

DO NOT USE CREATE TEMPORARY TABLE AT ALL because such tables only last as long as the DB connection lives, and would be private unto the call of the trigger also. Even worse off, if you are using MySQL Replication and you run STOP SLAVE on the slave, any tables created via CREATE TEMPORARY TABLE disappears from the SQL Thread and replication breaks immediately when you run START SLAVE and those temp tables no longer exist.

Otros consejos

This is a rather old question, so maybe this syntax didn't exist previously, but now you can just use SELECT INTO:

SELECT a, b INTO my_a, my_b FROM foo;

I find this to be aesthetically cleaner than the first syntax, and the query will only have to run once.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a dba.stackexchange
scroll top