如何让MySQL表主键自动递增?

时间:2015-11-05 03:14:51

标签: mysql mysql-workbench auto-increment

CREATE TABLE IF NOT EXISTS `mydb`.`Info_instrumental` (
  `id_instrument` INT NOT NULL COMMENT '',
  `instrument` VARCHAR(45) NOT NULL COMMENT '',
  `exp_ins` VARCHAR(45) NULL COMMENT '',
  `User_name_user` VARCHAR(45) NOT NULL COMMENT '',
  PRIMARY KEY (`id_instrument`, `User_name_user` `)  COMMENT '',
  INDEX `fk_Info_instrumental_User1_idx` (`User_name_user` ` ASC)  COMMENT '',
  CONSTRAINT `fk_Info_instrumental_User1`
    FOREIGN KEY (`User_name_user`)
    REFERENCES `mydb`.`Usuario` (`name_user`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

我想增加我的ID字段,如' 001',' 002',' 003' ....如何使用触发器执行此操作?

我想要这样的事情:

| id_instrument | instrument| exp_ins | User_name_user
------------------------------------------------------
|      001     | guitar    | 2 years |   Marcus
|      002     | piano     | 6 months|   Leo

1 个答案:

答案 0 :(得分:2)

您可以在创建表中使用zerofill关键字来查看您要搜索的结果。这是一个例子:

mysql> create table info_instrumental (
     >     id_instrument int(3) zerofill not null primary key auto_increment
     > );

mysql> insert into info_instrumental values (1), (2), (3);

mysql> select * from info_instrumental;
+---------------+
| id_instrument |
+---------------+
|           001 |
|           002 |
|           003 |
+---------------+

你不需要触发器来获得这样的结果。