如果日期匹配则更新Mysql触发器,如果​​不匹配则插入所有BEFORE INSERT

时间:2017-12-10 17:35:32

标签: mysql validation triggers insert

请原谅我的英语我正在使用语言翻译。
我有一张表summary,我希望在插入此表之前触发TRIGGER,即summary,我想要的是那个,TRIGGER应该检查传入日期是否与现有日期匹配,它应该更新表并将传入值添加到现有值,否则它应该只是插入

`summary`
+------+-------+-------------+------+
| date |income | expenditure | other|
|22/17 | 200   |   50        |  30  |
|22/17 | 100   |   10        |  80  |
|23/17 | 50    |   100       |  0   |
+------+-------+-------------+------+

`summary` // this is how i want it to be
+------+-------+-------------+------+
| date |income | expenditure | other|
|22/17 | 300   |   150       |  30  |
|23/17 | 50    |   100       |  0   |
+------+-------+-------------+------+

我的表格代码

CREATE TABLE `summary` (
  `id_` int(11) NOT NULL,
  `date_` date NOT NULL,
  `income_` text NOT NULL,
  `expenditure_` text NOT NULL,
  `other_` text NOT NULL,
  PRIMARY KEY(id) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `summary` 
(`id_`, `date_`, `income_`, `expenditure_`, `other_`)
VALUES
(1, '2017-12-22', 200, 50, 30),
(2, '2017-12-22', 100, 10, 80),
(3, '2017-12-23', 50, 100, 0);

这是我到目前为止所尝试的,虽然我是Novist 触发代码

DELIMITER
$$
CREATE TRIGGER inc_trig 
BEFORE INSERT 
ON income_
FOR EaCH ROW
BEGIN
DECLARE income,expenditure,other INT;

SET income=1; SET expenditure=2; SET other=3;

IF( NEW.date_ != date_ )THEN

IF NEW.name_ = income THEN
INSERT INTO summary (date_,income)
VALUES (new.date_,new.amount);

ELSEIF NEW.name_ = expenditure THEN
INSERT INTO summary (date_,expenditure_)
VALUES (new.date_,new.amount);

ELSEIF NEW.name_ = other THEN
INSERT INTO summary (date_,other_)
VALUES (new.date_,new.amount);


ELSE(new.date_ = date_)THEN

IF NEW.name_ = income_ THEN
UPDATE summary SET income_ = income_ + new.amount);

ELSEIF NEW.name_ = expenditure THEN
UPDATE summary SET expenditure_ = expenditure_ + new.amount);

ELSEIF NEW.name_ = other THEN
UPDATE summary SET other_ = other_ + new.amount);


END IF;

END
$$

1 个答案:

答案 0 :(得分:0)

有一种更简单的方法。首先,在unique列上添加date约束,以防止重复输入:

ALTER TABLE summary ADD CONSTRAINT summary_date_uniq UNIQUE(`date`);

然后在插入新数据时使用on duplicate key update语法:

INSERT INTO summary
(`date_`, `income_`, `expenditure_`, `other_`)
VALUES (2, '2017-12-22', 100, 10, 80)
ON DUPLICATE KEY UPDATE
`income` = `income_` + VALUES(`income_`),
`expenditure` = `expenditure_` + VALUES(`expenditure_`),
`others` = `others_` + VALUES(`others_`);