对于这种情况,如何在触发器中找到INNER JOIN的替代方案?

时间:2018-11-21 13:48:48

标签: postgresql triggers inner-join psql

我很难理解为什么使用内部联接函数cmd进行触发会导致错误: psql:createTrigger.sql:46:错误:“ currentStudentNumber”不是已知的变量LINE 8:选择COUNT(Student_subject.StudentID)到currentStudentNumber

       --rule, that lecturer can not have more than 7 students
CREATE FUNCTION lecturersStudentNumber() RETURNS "trigger" AS $$

DECLARE
    maxStudenNumber CONSTANT SMALLINT :=7;
    currentStudentNumber SMALLINT;
BEGIN

    SELECT  COUNT(Student_Subject.StudentID) INTO currentStudentNumber
FROM rora3887.Subject_Lecturer
INNER JOIN rora3887.Lecturer ON Subject_Lecturer.LecturerID=Lecturer.LecturerID
INNER JOIN rora3887.Subject ON Subject_Lecturer.SubjectID=Subject.SubjectID
INNER JOIN rora3887.Student_Subject ON Subject.SubjectID=Student_Subject.SubjectID
GROUP BY Lecturer.LecturerID;

    IF MAX(currentStudentNumber) + 1 > maxStudentNumber
        THEN RAISE EXCEPTION 'Lecturer can not have more than 7 students';
        END IF;
        RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER lecturersMaxStudentNumber
    BEFORE INSERT OR UPDATE ON rora3887.Subject_Lecturer
    FOR EACH ROW EXECUTE PROCEDURE lecturersStudentNumber();

我有一个包含此类代码的文件createTrigger.sql。 My database reliation scheme

1 个答案:

答案 0 :(得分:0)

问题出在关键字INTO

SELECT  COUNT(Student_Subject.StudentID) INTO currentStudentNumber

更改INTO --> AS

结果查询将是:

SELECT COUNT(Student_Subject.StudentID) AS currentStudentNumber

希望它能起作用:)