简体   繁体   English

自动增量触发

[英]Auto_increment trigger

I need to auto_increment the primary key in a mysql database using a trigger. 我需要使用触发器在MySQL数据库中自动递增主键。 Unfortunately, I am not quite sure how to do this. 不幸的是,我不太确定该怎么做。 In the sample code I have provided, I need the employee table primary key to auto_increment beginning with an empty table and a starting value of 200. Then, I need each new insert to increment by 1.Thanks for looking and I hope you are able to help me. 在我提供的示例代码中,我需要employee表主键为auto_increment,从一个空表开始,起始值为200。然后,我需要将每个新插入值增加1。感谢您的期待,希望您能够帮我。

CREATE TABLE department (
dept_name VARCHAR(50) NOT NULL  Primary Key
);

CREATE TABLE employee (
emp_id INT(6) unsigned Default 0 Not NULL 
, last_name VARCHAR(25) NOT NULL
, first_name VARCHAR(40) NOT NULL
, dept_name VARCHAR(50) NOT NULL
, PRIMARY KEY(emp_id, dept_name)
,  FOREIGN KEY(dept_name) REFERENCES department (dept_name)
);

There are several things you need to do: 您需要做几件事:

  1. Declare the emp_id column as AUTO_INCREMENT ; emp_id列声明为AUTO_INCREMENT
  2. Set the value of AUTO_INCREMENT property of the table to 200 ; 将表的AUTO_INCREMENT属性的值设置为200 ;
  3. Do not provide any value for column emp_id when you INSERT rows in table employee . 在表employee INSERT行时, 请勿emp_id列提供任何值。

Change the table creation as below: 更改表创建,如下所示:

CREATE TABLE employee (
    emp_id INT(6) UNSIGNED NOT NULL AUTO_INCREMENT,
    last_name VARCHAR(25) NOT NULL,
    first_name VARCHAR(40) NOT NULL,
    dept_name varchar(50) NOT NULL
    PRIMARY KEY(emp_id),
    FOREIGN KEY(dept_name) REFERENCES department_tbl(dept_name)
) AUTO_INCREMENT=200;

If the table has an AUTO_INCREMENT column then it must be the PRIMARY KEY of the table. 如果该表具有AUTO_INCREMENT列,则它必须是该表的PRIMARY KEY I removed dept_name from the definition of the PK above. 我从上面PK的定义中删除了dept_name I also removed the default value 0 from the emp_id column. 我还从emp_id列中删除了默认值0 It's default value is generated by MySQL using the AUTO_INCREMENT policy. 它的默认值是MySQL使用AUTO_INCREMENT策略生成的。

When you INSERT a new record into the employee table all you have to do is to not provide any value for the emp_id column: 当您INSERT一个新的记录到employee表中的所有您需要做的是提供任何的价值emp_id列:

INSERT INTO employee (last_name, first_name, dept_name)
VALUES ('Doe', 'John', 'accounting');

Then use the LAST_INSERT_ID() MySQL function to retrieve the value of the emp_id generated on insertion. 然后,使用LAST_INSERT_ID() MySQL函数检索插入时生成的emp_id的值。

The language or the library you use to develop the client application probably has a function that wraps LAST_INSERT_ID() and returns its value. 用于开发客户端应用程序的语言或库可能具有包装LAST_INSERT_ID()并返回其值的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM