Increment my id in my insert request

岁酱吖の 提交于 2019-12-24 15:33:37

问题


i have a table with some rows.

idClient, name, adress,country,...

i want to know how i can do an insert into this table with auto increment my idClient in my sql request..? Thx.

edit: i want do a request like this

insert into Client values((select max(idClient),...)

回答1:


ALTER TABLE Client CHANGE idClient
  idClient INT AUTO_INCREMENT PRIMARY KEY;

Then when you insert into the table, exclude the auto-incrementing primary key column from your insert:

INSERT INTO Client (name, address, country)
  VALUES ('name', 'address', 'country')...;

The new value of idClient will be generated.

This is the only way to do this safely if there are multiple instances of an application inserting rows at once. Using the MAX(idClient) method you describe will not work, because it's subject to race conditions.




回答2:


insert into Client values(NULL,"name","some address", "country")



回答3:


Define the id column as AUTO_INCREMENT, then skip the assignment altogether:

CREATE TABLE clients (
id MEDIUMINT NOT NULL PRIMARY KEY,
name VARCHAR(255),
addr VARCHAR(255),
country VARCHAR(255),
PRIMARY KEY (id));

INSERT INTO clients
(name, addr, country)
VALUES
("name", "addr", "country");


来源:https://stackoverflow.com/questions/2995719/increment-my-id-in-my-insert-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!