mySQL- Trigger更新COUNT基本插入值

时间:2017-04-16 08:44:14

标签: mysql

我想为mySQL创建一个触发器

  1. 将数据插入my table A(id, i_Year=2017, i_Number=NULL)

  2. 后触发
  3. 从表A中得到一个伯爵B:基本计算insert(New.i_Year)

  4. 将count-B更新为表A中的i_Number

    DELIMITER $$
    CREATE TRIGGER  update_1
    AFTER INSERT ON TABLEA
    FOR EACH ROW
    BEGIN
    
    UPDATE TABLEA
    SET TABLEA.i_Number = (SELECT COUNT(*)+1 FROM TABLEA WHERE TABLEA.i_Year = New.i_Year)
    FROM TABLEA 
    WHERE TABLEA.id = New.id;
    
    END$$
    DELIMITER ;
    
  5. 有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您可以将触发器更改为BEFORE INSERT并设置新行的计数,例如:

DELIMITER $$
CREATE TRIGGER  update_1
BEFORE INSERT ON TABLEA
FOR EACH ROW
BEGIN
DECLARE row_count int;

SELECT COUNT(*)+1 INTO row_count FROM TABLEA WHERE TABLEA.i_Year = New.i_Year
SET NEW.i_Number = row_count;

END$$
DELIMITER ;