我在TABLE之下,添加记录时工作正常
CREATE TABLE IF NOT EXISTS `certificates` (
`certyearmonth` varchar(6) NOT NULL DEFAULT '',
`certmonthnumber` mediumint(3) NOT NULL AUTO_INCREMENT,
`stockid` varchar(20) NOT NULL,
`checklisttemplateid` varchar(10) NOT NULL,
`certificateid` varchar(32) NOT NULL,
PRIMARY KEY (`certyearmonth`,`certmonthnumber`),
KEY `checklisttemplateid` (`checklisttemplateid`),
KEY `certificateid` (`certificateid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
添加记录时,certmonthnumber在同一个certyearmonth中计数+ 1。
201310 1
201310 2
201310 3
201311 1
201311 1
如何确定特定certyearmonth值的下一个auto_increment? 示例:如何在certyearmonth == 201310时确定certmonthnumber的下一个值, 或者当certyearmonth == 201401?
答案 0 :(得分:0)
您可以使用MAX()
查找当前最高值,然后将1添加到该值。使用COALESCE()
来处理表中尚未出现的certyearmonth值的情况,您可以使用相同的查询解决这两个示例:
mysql> select coalesce(max(certmonthnumber),0)+1 as next_val
-> from certificates
-> where certyearmonth = '201310';
+----------+
| next_val |
+----------+
| 4 |
+----------+
1 row in set (0.00 sec)
mysql>
mysql> select coalesce(max(certmonthnumber),0)+1 as next_val
-> from certificates
-> where certyearmonth = '201410';
+----------+
| next_val |
+----------+
| 1 |
+----------+
1 row in set (0.00 sec)