使用触发器从主表更新表

时间:2018-08-03 11:38:52

标签: mysql triggers

我具有以下结构:

主表X,存储销售的“标题”。

Y表,用于存储销售项目。

从表X触发的触发器中将保存一些销售数据的Z表。

在这种情况下,每次输入,更新或删除记录时,触发器都必须更新Z表中的值。

以下是已实现的代码:

插入后触发:

DROP TRIGGER IF EXISTS depoisInsertDADF311;

DELIMITER $$
CREATE TRIGGER depoisInsertDADF311 AFTER INSERT ON dadf311 
FOR EACH ROW BEGIN

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;

END;
$$

DELIMITER ;

删除后触发:

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 ;

0 个答案:

没有答案