MySQL 在插入后触发

MySQL Trigger on after insert(MySQL 在插入后触发)
本文介绍了MySQL 在插入后触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 MySQL 的新手.我有两个表 total_loaneravailable_loaner.我正在尝试为 total_loaner 中添加的每个新行创建一个触发器,我还想将该新行添加到 available_loaner.

I am new to MySQL. I have two tables total_loaner and available_loaner. I am trying to create a trigger for every new row added in total_loaner, I would also like to add that new row to available_loaner.

我的表格如下所示:

CREATE TABLE `total_loaner` (
  `Kind` varchar(10) NOT NULL,
  `Type` varchar(10) NOT NULL,
  `Sno` varchar(10) NOT NULL,
  PRIMARY KEY (`Sno`)
)

CREATE TABLE `available_loaner` (
  `Kind` varchar(10) NOT NULL,
  `Type` varchar(10) NOT NULL,
  `Sno` varchar(10) NOT NULL,
  `Status` char(10) NOT NULL DEFAULT '',
  PRIMARY KEY (`Sno`)
) 

我的触发器似乎不起作用.

My trigger does not seem to work.

CREATE TRIGGER new_loaner_added 
AFTER INSERT ON 'total_loaner' for each row
begin
INSERT INTO available_loaner (Kind, Type, Sno, Status)
Values (new.Kind, new.Type, new.Sno, 'Available');
END;

推荐答案

在你的情况下,你可以像这样重写触发器

In your case you can rewrite your trigger like this

CREATE TRIGGER new_loaner_added 
AFTER INSERT ON total_loaner
FOR EACH ROW 
  INSERT INTO available_loaner (Kind, Type, Sno, Status)
  VALUES (NEW.Kind, NEW.Type, NEW.Sno, 'Available');

注意:

  • 从表名total_loaner中删除单引号,因为引号有效地使其成为字符串文字而不是正确的标识符.如果需要,您可以使用反勾号,但这是不必要的,因为它不是保留字,也不包含任何特殊字符.
  • 因为它是一个单语句触发器,所以现在你不需要使用 DELIMITER 命令和 BEGIN...END
  • single quotes removed from table name total_loaner, because quotes effectively makes it a string literal instead of a proper identifier. You can use back ticks if you want but it's unnecessary since it's not a reserved word and it don't contain any special characters.
  • since it's a one-statement trigger now you don't need to use DELIMITER command and BEGIN...END block

这是SQLFiddle演示

Here is SQLFiddle demo

这篇关于MySQL 在插入后触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)