【发布时间】:2015-12-06 00:31:56
【问题描述】:
我有两张桌子学生和家庭。在学生中,我有列 st_income 和 total_income。在家里,我有收入。 Total_income 是学生的 st_income 和 family.id_student=student.id_student 的家庭收入的总和。
我想通过触发器更新 total_income,我做了这个
CREATE TRIGGER family_income_update AFTER UPDATE ON `family`
FOR EACH ROW UPDATE student SET total_income= ((SELECT SUM(income)
FROM family WHERE family.id_student=student.id_student)+
(SELECT st_income FROM student WHERE student.id_student=NEW.id_student))
WHERE student.id_student=NEW.id_student
MySQL 接受了这个触发器,但是当我想更新表族中的归档收入时,我得到了这样的沟通:
1093 - 您不能在 FROM 子句中指定目标表 'student' 进行更新
我不知道如何解决这个问题。
更新
我试过这个:
CREATE TRIGGER family_income_update AFTER UPDATE ON `family`
FOR EACH ROW
SET @familyIncome = SELECT SUM(income) FROM family WHERE family.id_student=student.id_student
SET @studentIncome= SELECT st_income FROM student WHERE student.id_student=NEW.id_student
SET @totalIncome=@familyIncome+@studentIncome
UPDATE student SET total_income=@totalIncome WHERE student.id_student=NEW.id_student
但我得到了这个答案:
1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 4 行的“SELECT SUM(income) FROM family WHERE family.id_student=student.id_student”附近使用正确的语法
更新
我尝试添加到 st_income 的 total_income 值。两列都在同一个表中。我试过这个:
CREATE TRIGGER `st_income_update` AFTER UPDATE ON `student`
FOR EACH ROW BEGIN
UPDATE student
SET total_income = total_income + (NEW.st_income - OLD.st_income)
WHERE student.id_student = NEW.id_student;
END
但它会导致错误。
【问题讨论】: