原始需求:
编号字段:L+年月日+十位流水号,例如:L201502090000000001 第二天的数据十位流水号又是从1开始
测试数据表以及触发器的建立如下:
SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for gztest -- ---------------------------- DROP TABLE IF EXISTS `gztest`; CREATE TABLE `gztest` ( `id` int(11) NOT NULL AUTO_INCREMENT, `code` bigint(20) DEFAULT NULL, `content` char(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8; DROP TRIGGER IF EXISTS `getcode`; DELIMITER ;; CREATE TRIGGER `getcode` BEFORE INSERT ON `gztest` FOR EACH ROW BEGIN declare newcode BIGINT; SET newcode=(SELECT `code` FROM gztest WHERE `code` LIKE CONCAT(DATE_FORMAT(curdate(),'%Y%m%d'),'%') ORDER BY `code` DESC LIMIT 1); IF newcode THEN SET NEW.code=newcode+1; ELSE SET NEW.code=CONCAT(DATE_FORMAT(curdate(),'%Y%m%d'),'0000000001'); END IF; END ;; DELIMITER ;