如何创建AUTO增量ID号

时间:2013-02-04 12:01:42

标签: php mysql phpmyadmin

如何创建年份和数字的自动增量ID号组成,例如:“2012-0001”如果输入其他数据,它将自动增加到“2012-0002”。

谢谢!

2 个答案:

答案 0 :(得分:2)

使用MyISAM,你可以这样做......

CREATE TABLE myisam_example(year INT NOT NULL,id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(year,id)) ENGINE=MyISAM;

INSERT INTO myisam_example VALUES (2012,NULL);
INSERT INTO myisam_example VALUES (2012,NULL);
INSERT INTO myisam_example VALUES (2012,NULL);
INSERT INTO myisam_example VALUES (2012,NULL);
INSERT INTO myisam_example VALUES (2012,NULL);
INSERT INTO myisam_example VALUES (2013,NULL);
INSERT INTO myisam_example VALUES (2013,NULL);
INSERT INTO myisam_example VALUES (2013,NULL);
INSERT INTO myisam_example VALUES (2013,NULL);
INSERT INTO myisam_example VALUES (2013,NULL);

SELECT * FROM myisam_example;
+------+----+
| year | id |
+------+----+
| 2012 |  1 |
| 2012 |  2 |
| 2012 |  3 |
| 2012 |  4 |
| 2012 |  5 |
| 2013 |  1 |
| 2013 |  2 |
| 2013 |  3 |
| 2013 |  4 |
| 2013 |  5 |
+------+----+

SELECT * 
  FROM myisam_example 
 WHERE CONCAT(year,'-',LPAD(id,5,0)) = '2012-00004';
+------+----+
| year | id |
+------+----+
| 2012 |  4 |
+------+----+

- 片刻对于糟糕指数的沉默沉思

SET @sql = CONCAT('SELECT * FROM myisam_example WHERE CONCAT(year,\'-\',LPAD(id,5,0)) = ?');

PREPARE stmnt1 FROM @sql;                
SET @a = '2012-00004';
EXECUTE stmnt1 USING @a;
+------+----+
| year | id |
+------+----+
| 2012 |  4 |
+------+----+
DEALLOCATE PREPARE stmnt1;

...并且更进了一步(因为我觉得是时候我知道如何在sprocs中使用预处理语句了...)

DROP PROCEDURE fetchid;
DELIMITER $$
CREATE PROCEDURE fetchid(IN a VARCHAR(10)) 
BEGIN
 SET @sql = CONCAT('SELECT * FROM myisam_example WHERE CONCAT(year,\'-\',LPAD(id,5,0)) = ?');
 PREPARE stmnt1 FROM @sql;                
 SET @a = a; 
 EXECUTE stmnt1 USING @a;
 DEALLOCATE PREPARE stmnt1;
END $$

DELIMITER ;

CALL fetchid('2012-00004');
+------+----+
| year | id |
+------+----+
| 2012 |  4 |
+------+----+

答案 1 :(得分:0)

你将不得不写一个程序来做到这一点。 Strawberry的解决方案向您展示了SQL需要做什么,但您必须编写您的接口(非sql)来分解输入,这样当用户输入2012-0001时,查询字符串会显示“WHERE”之类的内容年= 2012年和id = 0001“

如果你问你的表中是否有一个列可以有一个连字符然后自动递增,那么答案是否定的。