mysql event 简单demo

功能:每3秒删除b表数据,查询a表中的5条数据并插入b表。

/* 查看mysql事件状态 */
show variables like '%event_scheduler%';

/* 开启mysql事件 */
SET GLOBAL event_scheduler = ON;

/* 测试a表*/
CREATE TABLE `test_a` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `score_value` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

/* 测试b表*/
CREATE TABLE `test_b` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `score_value` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

/* 创建事件 */
CREATE EVENT IF NOT EXISTS event_test
/* 事件每三秒执行一次,也可以设置分minute或hour */
ON SCHEDULE EVERY 3 SECOND
ON COMPLETION PRESERVE
/* 使用proc_test存储过程 */
DO CALL proc_test();    
    
/* 创建proc_test存储过程 */    
DELIMITER // 
CREATE PROCEDURE proc_test() 
BEGIN 
/* 删除test_b表数据 */    
TRUNCATE TABLE test_b;
/* 1.查询test_a表数据,2.插入到test_b表 注意插入的数据中不能有id主键*/    
INSERT into test_b(score_value)select score_value from test_a where score_value = 5730 order by id desc limit 5;
END 
// 
DELIMITER ;

/* 查看存储过程 */    
show procedure status;
/* 查看事件 */    
show events
/* 删除事件 */    
drop event event_test
/* 删除存储过程 */    
drop procedure proc_test
发布了477 篇原创文章 · 获赞 588 · 访问量 267万+

猜你喜欢

转载自blog.csdn.net/qq_15037231/article/details/89711633