触发器-在插入另一个 table 时更新一个 table 中的列

Trigger- Update columns in one table on inserting in another table

所以,我有 2 个 table。

一个是 books,它具有以下字段。 accno(入藏号),name(书名),status(Issued/Not发行)

第二个是 total,它具有以下字段。 name(书名),count('Not Issued' 中 books table

的书数

我有一个在书table中添加书的表格,默认状态是'Not Issued'。 我还有一个发行书籍的表格,即将状态更改为 'Issued'。 我有一个 returns 书籍的表格,即将状态更改回 'Not Issued'。

我正在寻找一个触发器,它在每次 bookstable 更新时更新 total table 中的计数。 Count是图书table中可用(未发行)的图书数量,不同图书(书名)不同

我对触发器完全陌生。我环顾四周,但我似乎无法想出一种方法来实现这一点。

感谢任何帮助。谢谢你。

它看起来像一个库存系统,所以每次新书进入图书馆时,您都会将库存编号存储在 total table 中,当一本书根据 accnum库存减一,退货加一。

在这种情况下,应该使用以下触发器

delimiter //
create trigger book_available after update on books
for each row 
begin
 if new.status = 'Issued' then 
  update total set `count` = `count` - 1 where name = new.book_name ;
 else
  update total set `count` = `count` + 1 where name = new.book_name ;
 end if ;
 delimiter ;

这是一个测试用例

mysql> select * from books ;
+--------+-----------+------------+
| accnum | book_name | status     |
+--------+-----------+------------+
|      1 | AA        | Not Issued |
|      2 | AA        | Issued     |
|      3 | BB        | Not Issued |
+--------+-----------+------------+
3 rows in set (0.00 sec)


mysql> select * from total ;
+------+-------+
| name | count |
+------+-------+
| AA   |    20 |
| BB   |    30 |
+------+-------+
2 rows in set (0.00 sec)

mysql> delimiter //

mysql> create trigger book_available after update on books
    -> for each row 
    -> begin
    ->  if new.status = 'Issued' then 
    ->   update total set `count` = `count` - 1 where name = new.book_name ;
    ->  else
    ->   update total set `count` = `count` + 1 where name = new.book_name ;
    ->  end if ;
    -> end ;//
Query OK, 0 rows affected (0.13 sec)
mysql> delimiter ;

mysql> update books set status = 'Issued' where accnum = 1 ;
Query OK, 1 row affected (0.08 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from total ;
+------+-------+
| name | count |
+------+-------+
| AA   |    19 |
| BB   |    30 |
+------+-------+
2 rows in set (0.00 sec)


mysql> update books set status = 'Not Issued' where accnum = 1 ;
Query OK, 1 row affected (0.04 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from total ;
+------+-------+
| name | count |
+------+-------+
| AA   |    20 |
| BB   |    30 |
+------+-------+
2 rows in set (0.00 sec)