0

我在 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 或 certyearmonth==201401 时,如何确定 certmonthnumber 的下一个值?

4

1 回答 1

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)
于 2013-10-23T21:06:59.153 回答