Mysql trigger to update if date match and insert if no match all BEFORE INSERT
0
votes
2
answers
1358
views
please pardon my English i am using language translator.
I have a table
trigger code
I have a table
summary
,i want a TRIGGER to fire before insert on this table i.e summary
and what i want is that, the TRIGGER should check if the incoming date matches with existing date, it should update the table and add incoming value to existing value else it should just insert
my table codesummary
+------+-------+-------------+------+ | 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 TABLEThis is what i have been trying so far, though am a Novistsummary
(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 INTOsummary
(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);
trigger code
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 $$
Asked by Joshua Sampson
(5 rep)
Dec 10, 2017, 07:33 PM
Last activity: Aug 3, 2025, 01:03 AM
Last activity: Aug 3, 2025, 01:03 AM