I have the following structure:
A main table X, where the "header" of the sale is stored.
A Y table, where sales items are stored.
A Z table, where some sales data will be saved, from triggers fired from table X.
In this, every time you enter, update, or delete a record, the values in the Z-table will have to be updated by the trigger.
Follow the implemented codes:
Trigger AFTER INSERT:
DROP TRIGGER IF EXISTS depoisInsertDADF311;
DELIMITER $$
CREATE TRIGGER depoisInsertDADF311 AFTER INSERT ON dadf311
FOR EACH ROW BEGIN
/******** ALIMENTA TABELA DADF503 ********/
DELETE FROM dadf503 WHERE anomes = NEW.anomes;
INSERT INTO dadf503(anomes, codreg, nomreg, codsup, nomsup, codven, nomven, codpro, nompro, codcin, nomcin, valven, qtdven)
SELECT
dadf311.anomes, dadf311.codreg, dadf311.nomreg, dadf311.codsup, dadf311.nomsup,
dadf311.codven, dadf311.nomven, dadf313.produt AS codpro, dadf313.descri AS nompro,
dadf313.codcin, dadf313.nomcin, SUM(dadf313.valtot) AS valven, SUM(dadf313.quanti) AS qtdven
FROM
dadf311, dadf313
WHERE
dadf311.tipnot = 'NS' AND
dadf311.anomes = dadf313.anomes AND
dadf311.filial = dadf313.filial AND
dadf311.tipnot = dadf313.tipnot AND
dadf311.numnot = dadf313.numnot AND
dadf311.sequen = dadf313.sequen
GROUP BY anomes, codreg, codsup, codven, codpro
ORDER BY qtdven DESC;
/******** ALIMENTA TABELA DADF503 ********/
END;
$$
DELIMITER ;
Trigger AFTER DELETE:
DROP TRIGGER IF EXISTS depoisDeleteDADF311;
DELIMITER $$
CREATE TRIGGER depoisDeleteDADF311 AFTER DELETE ON dadf311
FOR EACH ROW BEGIN
UPDATE dadf503 AS vd1,
( SELECT dadf311.anomes, dadf311.codreg, dadf311.nomreg, dadf311.codsup, dadf311.nomsup,
dadf311.codven, dadf311.nomven, dadf313.produt AS codpro, dadf313.descri AS nompro,
dadf313.codcin, dadf313.nomcin, SUM(dadf313.valtot) AS valven, SUM(dadf313.quanti) AS qtdven
FROM dadf311, dadf313
WHERE dadf311.anomes = OLD.anomes AND
dadf311.anomes = dadf313.anomes AND
dadf311.filial = dadf313.filial AND
dadf311.tipnot = dadf313.tipnot AND
dadf311.numnot = dadf313.numnot AND
dadf311.sequen = dadf313.sequen AND
dadf311.tipnot = 'NS' ) AS vd2
SET vd1.anomes = vd2.anomes, vd1.codreg = vd2.codreg, vd1.nomreg = vd2.nomreg, vd1.codsup = vd2.codsup, vd1.nomsup = vd2.nomsup,
vd1.codven = vd2.codven, vd1.nomven = vd2.nomven, vd1.codpro = vd2.codpro, vd1.nompro = vd2.nompro, vd1.codcin = vd2.codcin,
vd1.nomcin = vd2.nomcin, vd1.valven = vd2.valven, vd1.qtdven = vd2.qtdven
WHERE vd1.anomes = vd2.anomes;
END;
$$
DELIMITER ;
My difficulty is in SELECT with WHERE, and if there is a way to narrow this query down to an easier form of mindset, because it visually looks "ugly."