要做一个累加的自增长,要求是每天清零重新计算,其实就是排号,但是因为某些原因又不能再内存中去做,只能写个存储过程在数据库中去做。
创建表,自增序列表
CREATE TABLE `t_sequence` (
`name` varchar(50) NOT NULL,
`current_value` int(11) NOT NULL,
`increment` int(11) NOT NULL DEFAULT '1',
`create_time` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='序列表,命名s_[table_name]'
两个存储过程函数
DELIMITER $$
USE `wxclouds`$$
DROP FUNCTION IF EXISTS `currval`$$
CREATE DEFINER=`root`@`%` FUNCTION `currval`(seq_name VARCHAR(50)) RETURNS INT(11)
READS SQL DATA
DETERMINISTIC
BEGIN
DECLARE VALUE INTEGER;
SET VALUE = 0;
SELECT current_value INTO VALUE FROM t_sequence WHERE NAME = seq_name;
RETURN VALUE;
END$$
DELIMITER ;
#############################################最主要的是下边这个
DELIMITER $$
USE `wxclouds`$$
DROP FUNCTION IF EXISTS `nextval`$$
CREATE DEFINER=`root`@`%` FUNCTION `nextval`(seq_name VARCHAR(50)) RETURNS INT(11)
DETERMINISTIC
BEGIN
DECLARE LASTTIME DATE ;
SELECT create_time INTO LASTTIME FROM t_sequence WHERE NAME = seq_name;
IF TO_DAYS(CURDATE())=TO_DAYS(LASTTIME)
THEN
UPDATE t_sequence SET current_value = current_value + increment, create_time =NOW() WHERE NAME = seq_name;
ELSE
UPDATE t_sequence SET current_value = 0 , create_time =NOW() WHERE NAME = seq_name;
END IF;
RETURN currval(seq_name);
END$$
DELIMITER ;
测试语句
SELECT nextval("5") ;