PostgreSQL AUTO INCREMENT(自動(dòng)增長(zhǎng))

2020-04-22 18:06 更新

AUTO INCREMENT(自動(dòng)增長(zhǎng))會(huì)在新記錄插入表中時(shí)生成一個(gè)唯一的數(shù)字。

PostgreSQL使用序列來(lái)標(biāo)識(shí)分區(qū)的自增長(zhǎng),數(shù)據(jù)類型有smallserial,serial和bigserial。這些屬性數(shù)據(jù)庫(kù)MySQL數(shù)據(jù)庫(kù)支持的AUTO_INCREMENT屬性。

使用MySQL設(shè)置自動(dòng)增長(zhǎng)的語(yǔ)句如下:

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這個(gè)屬性來(lái)標(biāo)識(shí)細(xì)分的自增。

PostgreSQL使用序列來(lái)標(biāo)識(shí)等級(jí)的自增長(zhǎng):

CREATE TABLE w3cschool
( id serial NOT NULL, alttext text, imgurl text )

SMALLSERIAL,SERIAL和BIGSERIAL范圍:

偽類型存儲(chǔ)大小范圍
SMALLSERIAL2字節(jié)1到32,767
SERIAL4字節(jié)1到2,147,483,647
BIGSERIAL8字節(jié)1到922,337,2036,854,775,807

語(yǔ)法

SERIAL數(shù)據(jù)類型基礎(chǔ)語(yǔ)法如下:

CREATE TABLE tablename (
   colname SERIAL
);

實(shí)例

預(yù)先我們要?jiǎng)?chuàng)建一張公司表,并創(chuàng)建以下幾個(gè)分段:

w3cschooldb=# CREATE TABLE COMPANY(
   ID  SERIAL PRIMARY KEY,
   NAME           TEXT      NOT NULL,
   AGE            INT       NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

現(xiàn)在往表中插入幾條記錄:

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


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)