插入后和更新后的MySQL触发器

时间:2011-03-05 03:38:57

标签: mysql sql triggers

我有两个表,其中一个名为att,如下所示

CREATE TABLE att (
  SID varchar(50) NOT NULL, 
  CID varchar(50) NOT NULL, 
  Date date NOT NULL,
  H1 varchar(1) NOT NULL DEFAULT 0,
  H2 varchar(1) NOT NULL DEFAULT 0,
  H3 varchar(1) NOT NULL DEFAULT 0,
  H4 varchar(1) NOT NULL DEFAULT 0,
  H5 varchar(1) NOT NULL DEFAULT 0,
  H6 varchar(1) NOT NULL DEFAULT 0,
  H7 varchar(1) NOT NULL DEFAULT 0,
  H8 varchar(1) NOT NULL DEFAULT 0,
  H9 varchar(1) NOT NULL DEFAULT 0,
  H10 varchar(1) NOT NULL DEFAULT 0,
  INDEX (SID, CID)
);

另一个表是per,其中包含以下字段:
SID CID每

如何为以下内容编写触发器:
如果在att表上的h1-h0的任何字段中发生更新,则为 使用以下值更新per表中的per列:
((1的总数 - 0的总数)/(1的总数+ 0的总数))/ 100

提前致谢
我开发了一个触发器,但它没有工作,它在第11行说错误,你能说出来是什么问题吗?

create TRIGGER `att_up` AFTER UPDATE ON `attentance`
FOR EACH ROW BEGIN
  DECLARE Zeros INT;
  DECLARE Ones INT;
  DECLARE total INT;
  DECLARE atted FLOAT;
  SELECT SUM(8-(h1+h2+h3+h4+h5+h6+h7+h8)) 
      INTO Zeros FROM attentance 
      WHERE StudID=NEW.StudID;
  SELECT SUM(h1+h2+h3+h4+h5+h6+h7+h8) 
      INTO Ones FROM attentance 
      WHERE StudID=NEW.StudID;
  SELECT SUM(8-(h1+h2+h3+h4+h5+h6+h7+h8))+ SUM(h1+h2+h3+h4+h5+h6+h7+h8) 
      INTO total FROM attentance 
      WHERE StudID=NEW.StudID;
  set atted=((ZEROS-Ones)/total)/100;
  INSERT into per(per) values (atted);
END$$

2 个答案:

答案 0 :(得分:3)

确保在定义触发器之前更改分隔符。还要确保在创建表格和触发器时使用相同的表格和列名称(您使用attattendance以及SIDStudID ,在你的例子中)。

实际上,在设置分隔符后,我在MySQL 5.1.55中测试时,触发器定义没有引起任何错误。

delimiter $$
CREATE TRIGGER `att_up` 
  AFTER UPDATE ON `attendance`
FOR EACH ROW 
BEGIN
  DECLARE Zeros INT;
  DECLARE Ones INT;
  DECLARE total INT;
  DECLARE attend FLOAT;
  SELECT SUM(8-(h1+h2+h3+h4+h5+h6+h7+h8)), 
         SUM(h1+h2+h3+h4+h5+h6+h7+h8),
         SUM(8-(h1+h2+h3+h4+h5+h6+h7+h8)) + SUM(h1+h2+h3+h4+h5+h6+h7+h8)
    INTO Zeros, Ones, Total FROM attendance 
    WHERE SID=NEW.SID;
  SET attend=((Zeros-Ones)/total)/100;
  INSERT INTO per (SID, CID, per) values (NEW.SID, NEW.CID, attend)
    ON DUPLICATE KEY UPDATE per=attend;
END$$
delimiter ;

答案 1 :(得分:-1)

DELIMITER $$

CREATE TRIGGER `att_up` AFTER UPDATE ON `attentance`
FOR EACH ROW

BEGIN

SET @zeros = 0;
SET @ones = 0;
SET @total = 0;
SET @atted = 0;


(SELECT (8-SUM(h1)+SUM(h2)+SUM(h3)+SUM(h4)+SUM(h5)+SUM(h6)+SUM(h7)+SUM(h8)) INTO @zeros FROM attentance WHERE StudID=NEW.StudID);
(SELECT SUM(h1+h2+h3+h4+h5+h6+h7+h8) INTO @ones FROM attentance WHERE StudID=NEW.StudID);
(SELECT (SUM(8-(h1+h2+h3+h4+h5+h6+h7+h8))+ SUM(h1+h2+h3+h4+h5+h6+h7+h8)) INTO @total FROM attentance WHERE StudID=NEW.StudID);

SELECT (((@zeros-@ones)/@total)/100) INTO @atted FROM (SELECT 1) AS x;

END$$