使用MySQL Trigger插入或更新行

时间:2017-07-17 10:31:44

标签: mysql triggers mariadb

我有两个MySQL表:smsconsumptionsms表包含所有事务,而consumption表包含消耗的短信总和。

我的目标是能够实现一天的实际消费,所以我只需要直接在consumption表上查看。 对于它,我试图创建一个将验证的触发器:

  1. 如果第1天consumption表中没有行,则插入新行
  2. 如果第1天已有一行,则更新
  3. 这里我的代码不起作用。

    CREATE TRIGGER tg_new_sms_sent
    AFTER INSERT ON sms
    FOR EACH ROW
        SET @k = (SELECT id FROM consumption WHERE period = NEW.simple_date);
        CASE
            WHEN ISNULL(@k) THEN
                INSERT INTO consumption (system_id, period, credit, sms)
                VALUES (NEW.system_id, NEW.simple_date, NEW.used_credit, NEW.sms_count);
            ELSE
                UPDATE consumption SET credit = credit + New.used_credit, sms = sms + NEW.sms_count WHERE (system_id = NEW.system_id) AND (period = NEW.simple_date);
        END CASE
    

    我该怎么办?

2 个答案:

答案 0 :(得分:1)

 private def newJWT(..., private: String, public: String) = Try {
  val privateKey: RSAPrivateKey = ???
  val publicKey: RSAPublicKey = ???


  val algorithm: Algorithm = Algorithm.RSA256(publicKey, privateKey)
  val token: String = JWT.create().
    // ...
    .sign(algorithm)
  // ...
  token
}

尝试以上查询。

答案 1 :(得分:1)

尝试以下代码。

DELIMITER $$
CREATE TRIGGER tg_new_sms_sent
AFTER INSERT ON sms
FOR EACH ROW
  BEGIN
    DECLARE num_rows INT;

    SELECT COUNT(id) INTO num_rows FROM consumption
    WHERE system_id = NEW.system_id AND period = NEW.simple_date;

    IF num_rows = 0 THEN
        INSERT INTO consumption (system_id, period, credit, sms)
        VALUES (NEW.system_id, NEW.simple_date, NEW.used_credit, NEW.sms_count);
    ELSE
        UPDATE consumption
        SET credit = credit + NEW.used_credit, sms = sms + NEW.sms_count
        WHERE system_id = NEW.system_id AND period = NEW.simple_date;
    END IF;

  END$$
DELIMITER ;