mysql - MySQL 触发器获取文本变量
问题描述
假设我们有两张桌子。
第一个表是项目- id, title
。
第二张表是历史- id, title, action, user
。
我们可以为“此用户插入此项目”设置以下 AFTER INSERT 触发器:
INSERT INTO history (title, action, user) VALUES (NEW.title, 'INSERT', @phpUserId);
如果我想插入新项目,我可以这样做。
SET @phpUserId = 123;
INSERT INTO items (title) VALUES ('My best item');
在这种情况下,触发器完美地工作。
但问题是,当我将一些文本添加到变量中时——例如SET @phpUserId = "library123";
——此时触发器无法获取该变量。
任何想法为什么只传递整数变量?
解决方案
好消息,您的触发器没有问题,这是证据
drop table if exists i,h;
create table i(id int, title varchar(20));
create table h(id int, title varchar(20), action varchar(20), user varchar(30));
drop trigger if exists t;
delimiter $$
create trigger t after insert on i
for each row
begin
INSERT INTO h (title, action, user) VALUES (NEW.title, 'INSERT', @phpUserId);
end $$
delimiter ;
SET @phpUserId = 123;
INSERT INTO i (title) VALUES ('My best item');
SET @phpUserId = 'bob123';
INSERT INTO i (title) VALUES ('My worst item');
+------+---------------+--------+--------+
| id | title | action | user |
+------+---------------+--------+--------+
| NULL | My best item | INSERT | 123 |
| NULL | My worst item | INSERT | bob123 |
+------+---------------+--------+--------+
2 rows in set (0.00 sec)
推荐阅读
- spring-integration - 带有“.”的标题注释 在标题名称中,例如 @Header("foo.bar"),不映射
- javascript - 根据多个值过滤对象,只返回完美匹配
- java - Apache Karaf - 缺少依赖项(似乎是数据源)
- ios - 将“每次询问”指定为 Siri 意图中参数的默认值
- json - 使用 jq 基于 key 和 type 对 JSON 值进行条件转换
- naming-conventions - 你如何命名一个包含字符串中每个字母的 List 对象
- python - 如何在 macOS 上的 PyCharm 中使用 Matplotlib.animation.FuncAnimation 显示动画图形?
- c - 为什么这个程序会导致无限循环输出?
- java - 试图创建一个案例来识别多个字符
- css - 我下拉列表中的文本被下面的手风琴隐藏