![](/img/trans.png)
[英]Trigger after update with value depend on other row with same field and table
[英]Using computed value or trigger to update a row with data from a different row in the same table?
我想為mainKey = 1
插入2019-08-15
的mainKey = 1
,如果總數在2019-08-14
上大於200
,我想將差異保存在為2019-08-15
創建的新行中的最后一列中2019-08-15
。 total
是可以保持不變或增加的值。
+------------+---------+-------+--------------------------+
| date | mainKey | total | differenceSinceYesterday |
+------------+---------+-------+--------------------------+
| 2019-08-14 | 1 | 200 | 0 |
| 2019-08-14 | 2 | 500 | 0 |
+------------+---------+-------+--------------------------+
date
和mainKey
共同唯一標識該行,因此特定mainKey
的行每天只能插入一次。
+--------------------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------------------+---------+------+-----+---------+-------+
| date | date | NO | PRI | NULL | |
| mainKey | int(11) | NO | PRI | NULL | |
| total | int(11) | NO | | NULL | |
| differenceSinceYesterday | int(11) | NO | | NULL | |
+--------------------------+---------+------+-----+---------+-------+
我查看了觸發器,但是如果運行AFTER UPDATE,它將變為遞歸的,因為它是同一張表。 還是應該將邏輯轉移到確實要首先插入並運行另一個SELECT
的外部腳本中,以查找具有特定mainKey
第一天的行並更新今天的行?
你可以實現你想要的一個BEFORE INSERT
觸發器,檢查一total
來自> = 200的前一天值,如果它存在,則設置differenceSinceYesterday
值到今天的和昨天的總數之間的區別:
DELIMITER //
CREATE TRIGGER updateDifference
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
DECLARE yesterday INT;
SELECT total INTO yesterday FROM table1 WHERE date = NEW.date - INTERVAL 1 DAY AND mainKey = NEW.mainKey;
IF yesterday >= 200 THEN
SET NEW.differenceSinceYesterday = NEW.total - yesterday;
END IF;
END;
DELIMITER ;
INSERT INTO table1 (date, mainKey, total)
VALUES ('2019-08-15', 1, 400), ('2019-08-16', 1, 300);
SELECT * FROM table1
輸出:
date mainKey total differenceSinceYesterday
2019-08-14 00:00:00 1 200 0
2019-08-14 00:00:00 2 500 0
2019-08-15 00:00:00 1 400 200
2019-08-16 00:00:00 1 300 -100
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.