PostgreSQL AUTO INCREMENT(自动增长)
AUTO INCREMENT(自动增长)会在新记录插入表中时生成一个唯一的数字。
PostgreSQL使用序列来标识分区的自增长,数据类型有smallserial,serial和bigserial。这些属性数据库MySQL数据库支持的AUTO_INCREMENT属性。
使用MySQL设置自动增长的语句如下:
CREATE TABLE IF NOT EXISTS `w3cschool_tbl`( `w3cschool_id` INT UNSIGNED AUTO_INCREMENT, `w3cschool_title` VARCHAR(100) NOT NULL,
`w3cschool_author` VARCHAR(40) NOT NULL,
`submission_date` DATE, PRIMARY KEY ( `w3cschool_id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
MySQL是用AUTO_INCREMENT这个属性来标识细分的自增。
PostgreSQL使用序列来标识等级的自增长:
CREATE TABLE w3cschool
( id serial NOT NULL, alttext text, imgurl text )
SMALLSERIAL,SERIAL和BIGSERIAL范围:
伪类型 | 存储大小 | 范围 |
---|---|---|
SMALLSERIAL | 2字节 | 1到32,767 |
SERIAL | 4字节 | 1到2,147,483,647 |
BIGSERIAL | 8字节 | 1到922,337,2036,854,775,807 |
语法
SERIAL数据类型基础语法如下:
CREATE TABLE tablename ( colname SERIAL );
实例
预先我们要创建一张公司表,并创建以下几个分段:
w3cschooldb=# CREATE TABLE COMPANY( ID SERIAL PRIMARY KEY, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL );
现在往表中插入几条记录:
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'Paul', 32, 'California', 20000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ('Allen', 25, 'Texas', 15000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ('Teddy', 23, 'Norway', 20000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'Mark', 25, 'Rich-Mond ', 65000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'David', 27, 'Texas', 85000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'Kim', 22, 'South-Hall', 45000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'James', 24, 'Houston', 10000.00 );
查看公司表的记录如下:
id | name | age | address | salary ----+-------+-----+------------+-------- 1 | Paul | 32 | California | 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall | 45000 7 | James | 24 | Houston | 10000