trigger error to update a column with the sum of 2 other column

只谈情不闲聊 提交于 2019-12-11 12:07:30

问题


I have a simple table called 'followers':

id fb tw sum 
1   2  4  
2   6  5
3   4  8

I want to create a trigger such that after inserting data into the 'fb' and 'tw' columns, the fourth colum 'sum' will be the sum of fb+tw.

Here is my code for the trigger:

USE `my_database`;
DELIMITER $$
CREATE TRIGGER `followers_AINS` AFTER INSERT ON `followers` FOR EACH ROW 
BEGIN
UPDATE sum SET sum=fb+tw
END
DELIMITER;

I keep getting a DDL error.


回答1:


Use a before trigger. And set the values with the NEW keyword to indicate the currently inserted record

DELIMITER $$
CREATE TRIGGER `followers_AINS` BEFORE INSERT ON `followers` 
FOR EACH ROW 
BEGIN
  SET NEW.sum = NEW.fb + NEW.tw;
END
$$
DELIMITER ;

Also use a space between delimiter and the actual delimiter to change the definition.



来源:https://stackoverflow.com/questions/25126748/trigger-error-to-update-a-column-with-the-sum-of-2-other-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!