我在数据库中有一个结构,我有一个问题表,结果有4列,所以int id,string question,int a,int b,int c,int d
答案表有int id,int user_id,int question_id,string answer。
现在答案表中的答案可以是a,b,c或d,在问题表中我有每个答案的数量。
我想要做的是创建一个触发器,当插入新的答案时,该触发器将自动增加相应列的值。
DELIMITER $$
DROP TRIGGER IF EXISTS `answer_INSERT` $$
CREATE TRIGGER `answer_INSERT`
AFTER INSERT ON `answer`
FOR EACH ROW
BEGIN
IF(answer.answer LIKE ('a'))
UPDATE `question` SET `a`=`a`+1 WHERE `id`=answer.question_id
ELSE IF(answer.answer LIKE ('b'))
UPDATE `question` SET `b`=`b`+1 WHERE `id`=answer.question_id
....
END $$
DELIMITER ;
我知道代码不是很正确,但这或多或少都是我要做的。
答案 0 :(得分:0)
DELIMITER $$
DROP TRIGGER IF EXISTS `answer_INSERT` $$
CREATE TRIGGER `answer_INSERT`
AFTER INSERT ON `answer`
FOR EACH ROW
BEGIN
IF NEW.answer = 'a' THEN
UPDATE `question` SET `a` = `a`+1 WHERE `id` = NEW.question_id;
ELSEIF NEW.answer = 'b' THEN
UPDATE `question` SET `b` = `b`+1 WHERE `id` = NEW.question_id;
END IF;
END $$
DELIMITER ;