mysql - 带有游标的Mysql触发器以从一个表中获取所有列并插入到另一个表中
问题描述
我有两个表产品和产品日志。当我在产品表中插入、更新或删除记录时,我想调用执行以下操作的触发器
1:- fetch all column name from product table.
2:- arrange product table column name and value in json format
e.g. log = {"col_first":"value_first", "col_second":"value_second"}
3:- After that insert into product log.
product table
create table product(
id int auto_increment primary key,
name varchar(100),
description text,
created_at datetime
);
product_log table
create table product_log(
id int auto_increment primary key,
table_name varchar(100),
logdata longtext,
created_at datetime
);
这是我的触发代码,不正确请朋友们帮助我。任何建议将不胜感激。谢谢你
DELIMITER $$
create trigger after_product_insert
AFTER INSERT on product for each ROW
BEGIN
DECLARE finished INTEGER DEFAULT 0;
declare stProduct text;
DECLARE stRes text;
declare prodct cursor for SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='mydb' AND TABLE_NAME='product';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN prodct;
stLoop: LOOP
FETCH prodct INTO stProduct;
IF finished = 1 THEN
LEAVE stLoop;
END IF;
SET stRes = CONCAT(stProduct,",",stRes);
END LOOP stLoop;
insert into product_log(table_name, logdata) values ('product', stRes);
CLOSE prodct;
END$$
DELIMITER ;
查询运行表后如下所示:
Product table
|----------|----------|------------------|---------------------|
| id | name | description | created_at |
|----------|----------|------------------|---------------------|
| 1 | laptop | all about laptop | 2020-01-29 00:00:00 |
|----------|----------|------------------|---------------------|
product_log table
|----------|----------------|---------------------------------------------|---------------------|
| id | table_name | logdata | created_at |
|----------|----------------|---------------------------------------------|---------------------|
| 1 | product | {"name":"laptop","description":"all ..",..} | 2020-01-29 00:00:00 |
|----------|----------------|---------------------------------------------|---------------------|
解决方案
如果只是concat,则不能用作json。
json_set(columnname, key, value[, key, value]);
其次,如果您只想要长文本中的值对,您可以使用
select group_concat( concat(name, ":", description) SEPARATOR ",")...
推荐阅读
- docker - Azure DevOps 服务器 (onprem) - 容器作业 - 结帐不起作用
- mongodb - 如何在 MongoDB 中编写查询以滚动获取过去 7 天的数据
- python - 为什么在 Ubuntu 18.04 上运行 Selenium chrome 驱动程序时 chrome 浏览器不启动
- uri - 区分电子邮件地址和 IRI
- flutter - 有没有办法在 Flutter/Dart 中添加导航路线列表?
- c# - 在场景完全加载之前调用 Unity start()
- flutter - 有没有办法在 Flutter/Dart 中添加导航路线列表?
- javascript - 如何在 Nuxt Vue 实例中获取 Discord.js 客户端
- python-2.7 - 如何使用python将字典键值写入文本文件
- r - Firth 的惩罚逻辑回归 - 高卡方值