MySQL Trigger on after insert(MySQL 在插入后触发)
问题描述
我是 MySQL 的新手.我有两个表 total_loaner
和 available_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 andBEGIN...END
block
这是SQLFiddle演示
Here is SQLFiddle demo
这篇关于MySQL 在插入后触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL 在插入后触发
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- SQL 临时表问题 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01