I have beneath TABLE and it's working fine when adding a record
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 ;
When adding a record the certmonthnumber is counting+1 within the same certyearmonth.
201310 1
201310 2
201310 3
201311 1
201311 1
How can I determine the next auto_increment on a specific certyearmonth value? Example: How can I determine the next value for certmonthnumber when certyearmonth==201310, or when certyearmonth==201401?
You can use MAX()
to find the current highest value, then add 1 to that value. Use COALESCE()
to handle the case of certyearmonth values that are not yet present in the table, and you can solve both of your examples with the same query:
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)