问题
User Table:
ID Name
1 usr1
2 usr2
3 usr3
In the above table, ID is a primary key. My requirement is while inserting data into the table, I would like to specify only the
name like INSERT INTO user VALUES('usr4')
. After execute the query, Is there any way to automatically create ID for 'usr4'?
I tried with serial data type. For that also we have to specify the keyword default like INSERT INTO user VALUES(default,'usr4')
. So, is there any way to do like INSERT INTO user VALUES('usr4')
. NOTE: ID should be unique.
回答1:
Use the built-in data type serial
or bigserial
.
create table users (
id serial primary key,
name varchar(100) not null unique -- ?
);
Name the column(s); omit the name of the serial or bigserial column.
insert into users (name) values ('usr4');
The general rule is that you have to supply one value for each column used in an INSERT statement. If you don't specify column names, you have to supply a value for every column, including "Id", and you have to supply them in the order the columns appear in the table.
If you specify column names, you can omit columns that have defaults and columns that are nullable, and you can put the column names in any order. The order of the values has to match the order of the column names you specify.
来源:https://stackoverflow.com/questions/35763115/generate-auto-id-in-postgresql