代码之家  ›  专栏  ›  技术社区  ›  Dipak

仅当不重复时才插入mysql触发器

  •  1
  • Dipak  · 技术社区  · 6 年前

    我对使用触发器事件来获得预期结果有点困惑

    这里是主桌 fee

    id  |   rn  |   fid |   amount  |   f_month |   year
    ====================================================
    1   |   1   |   1   |   150000  |   1       |   1
    2   |   1   |   2   |   50000   |   1       |   1
    3   |   2   |   1   |   550500  |   2       |   1
    4   |   2   |   2   |   200     |   2       |   1
    5   |   3   |   1   |   550500  |   2       |   1
    

    DROP TRIGGER IF EXISTS `insertinv`;
    CREATE DEFINER=`root`@`localhost` TRIGGER `insertinv`
    AFTER INSERT ON `fee` FOR EACH ROW INSERT INTO invoice VALUES(null, NEW.rn, NEW.year, '') 
    

    inv |   rn  |   y_d |   status  
    ==============================
    1   |   1   |   1   |   0
    2   |   1   |   1   |   0
    3   |   2   |   1   |   0
    4   |   2   |   1   |   0
    5   |   3   |   1   |   0
    

    如果 fee.rn 以及 fee.f_month 以及 fee.year fee.fid .

    并取得以下成果。期望的那个

    发票联

    inv |   rn  |   y_d |   status  
    ==============================
    1   |   1   |   1   |   0
    2   |   2   |   1   |   0
    3   |   3   |   1   |   0
    

    inv

    1 回复  |  直到 6 年前
        1
  •  1
  •   Madhur Bhaiya    6 年前
    • 检查是否 inv year rn .
    • 如果不存在,则使用 insert 声明。

    DELIMITER $$
    DROP TRIGGER IF EXISTS `insertinv` $$
    
    CREATE DEFINER=`root`@`localhost` TRIGGER `insertinv`
    AFTER INSERT ON `fee` 
    FOR EACH ROW 
      BEGIN
    
        /* Declare a variable to store invoice id for matching year and rn */
        DECLARE inv_exists INT(11) DEFAULT 0;
    
        /* Fetch the invoice id if exists */
        SELECT inv INTO inv_exists 
        FROM invoice 
        WHERE rn = NEW.rn AND 
              y_d = NEW.year; 
    
        /* if no invoice exists then insert into the table */
        IF NOT(inv_exists > 0) THEN 
    
            /* Insert statement */
            INSERT INTO invoice VALUES(null, NEW.rn, NEW.year, '') ;
    
        END IF;
    END $$
    DELIMITER ;