我的数据库中有三个表 - Students
,Books
和Books2student
。
Students
表格有StudentID, First_Name, Last_Name
。
Books
表格有ISBN_no, name, no. of copies available
。
Books2Students
表格中有StudentID, books issued, issue date, due date
。
我想创建一个触发器,当学生从books2students
删除时,no. of copies
表中的Books
应该增加,如果我在books2student
中插入一本书,那么书中no of copies
应该减少。
我写了一个函数和触发器,但是我在函数中遇到错误
CREATE FUNCTION student_to_book() RETURNS trigger AS '
BEGIN
IF tg_op = ''DELETE'' THEN
UPDATE books
SET books.no_of_copies_available = no_of_copies_available+1
WHERE Books2Students.Book_Issued=books.ISBN_no;
END IF;
IF tg_op = ''INSERT'' THEN
UPDATE books
SET books.no_of_copies_available = no_of_copies_available-1
WHERE Books2Students.Book_Issued=books.ISBN_no;
END IF;
END
' LANGUAGE plpgsql;
我收到错误错误:
ERROR: missing FROM-clause entry for table "books2students" Where: PL/pgSQL function student_to_book() line 10 at SQL statement
答案 0 :(得分:0)
您收到错误是因为您指的是WHERE
子句中的books books2students,但没有FROM
子句。我假设触发器是针对此表的,因此您可以在更新部件中使用关键字NEW
,在删除部件中使用关键字OLD
而不是表名。像这样:
IF tg_op = ''INSERT'' THEN
UPDATE books
SET books.no_of_copies_available = no_of_copies_available-1
WHERE NEW.Book_Issued=books.ISBN_no;
答案 1 :(得分:0)
有很多问题。这可能有效:
CREATE OR REPLACE FUNCTION student_to_book()
RETURNS trigger AS
$func$
BEGIN
IF TG_OP = 'DELETE' THEN
UPDATE books
SET no_of_copies_available = no_of_copies_available + 1
WHERE ISBN_no = OLD.Book_Issued;
ELSIF TG_OP = 'INSERT' THEN
UPDATE books
SET no_of_copies_available = no_of_copies_available - 1
WHERE ISBN_no = NEW.Book_Issued;
END IF;
END
$func$ LANGUAGE plpgsql;
Start by reading the manual about the special records OLD
and NEW
here.
Then read the manual about UPDATE
here.
你还没有覆盖TG_OP = UPDATE
。
通常,MATERIALIZED VIEW
是一种更好的方法来跟踪每本书的计数。