1
    CREATE TABLE IF NOT EXISTS `test` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `ia_att` decimal(3,2) NULL,
      `t1` decimal(3,2) NULL,
      `t2` decimal(3,2) NULL,
      `t3` decimal(3,2) NULL,
      `ia_tot` decimal(3,2) NULL,
      .....
      .....
      PRIMARY KEY (`id`),
    );      

 CREATE TRIGGER tg_bi_test
    BEFORE INSERT ON test
    FOR EACH ROW 
      SET NEW.s1_ia_tot = 
         (NEW.s1_t1 + NEW.s1_t2 + NEW.s1_t3 -
          LEAST(NEW.s1_t1, NEW.s1_t2, NEW.s1_t3)) / 2 + 
         CASE 
           WHEN NEW.s1_ia_att > 95 THEN 5
           WHEN NEW.s1_ia_att BETWEEN 81 AND 95 THEN 4
           WHEN NEW.s1_ia_att BETWEEN 76 AND 80 THEN 3
           WHEN NEW.s1_ia_att BETWEEN 61 AND 75 THEN 2
           WHEN NEW.s1_ia_att < 60 THEN 0 

      SET NEW.s2_ia_tot = 
         (NEW.s2_t1 + NEW.s2_t2 + NEW.s2_t3 -
          LEAST(NEW.s2_t1, NEW.s2_t2, NEW.s2_t3)) / 2 + 
         CASE 
           WHEN NEW.s2_ia_att > 95 THEN 5
           WHEN NEW.s2_ia_att BETWEEN 81 AND 95 THEN 4
           WHEN NEW.s2_ia_att BETWEEN 76 AND 80 THEN 3
           WHEN NEW.s2_ia_att BETWEEN 61 AND 75 THEN 2
           WHEN NEW.s2_ia_att < 60 THEN 0
           --------
           --------
         END;

创建这样的触发器有什么问题?我想为一张表中的 ia_tot 的七个列创建这个请帮助我这在 mysql 中是否可行

4

1 回答 1

0

一点提示 - 创建一个用户定义的函数来执行所有计算:

delimiter $$
create function my_calculation( ia_att decimal, t1 decimal, t2 decimal, t3 decimal )
returns int
deterministic 
begin 
  RETURN
  (t1 + t2 + t3 - LEAST(t1, t2, t3)) / 2
  +
  CASE 
    WHEN ia_att > 95 THEN 5
    WHEN ia_att BETWEEN 81 AND 95 THEN 4
    WHEN ia_att BETWEEN 76 AND 80 THEN 3
    WHEN ia_att BETWEEN 61 AND 75 THEN 2
    WHEN ia_att < 60 THEN 0 
   END;
END $$
DELIMITER ;

并在您的触发器中使用此功能:

delimiter $$
create trigger abc before insert 
on `test` for each row
begin
   declare `value` decimal;

   SET NEW.s1_ia_tot = my_calculation( NEW.s1_ia_att, NEW.s1_t1, NEW.s1_t2, NEW.s1_t3 );
   SET NEW.s2_ia_tot = my_calculation( NEW.s2_ia_att, NEW.s2_t1, NEW.s2_t2, NEW.s2_t3 );
   SET NEW.s3_ia_tot = my_calculation( NEW.s3_ia_att, NEW.s3_t1, NEW.s3_t2, NEW.s3_t3 );
   ......
end $$
delimiter ; 

这将使您的代码更短、更清晰、更易于维护。

另一个备注 - DECIMAL(3,2) 存储最多 3 位数字,小数点右侧 2 位数字。也就是说,小数点左侧只有一位( 3 - 2 = 1 ),并且最多只能存储 9.99 的数字,不能更多。如果数量为 10 或更多,您将收到错误消息。

---- 编辑 -----
这是一个工作演示的链接 --> http://sqlfiddle.com/#!2/93c8d/4

于 2013-09-15T12:06:07.733 回答