2015-12-02 3 views
9

シーケンスを選択したほうがいいときと、シリアルを使う方が良いときは です。Postgresql Sequence vs Serial

私は PostgreSQL Autoincrement

は、私は決して前にシリアルを使用していない、この質問を読ん

SELECT LASTVAL(); 

使用して挿入した後、最後の値を返して欲しいです。

+0

あなたはそのシリアルまたはシーケンスを挿入したものに割り当てられている場合は、それは '' 'RETURNING'''ステートメントを使用することをお勧めします。 http://stackoverflow.com/questions/19167349/postgresql-insert-from-select-returning-id –

+0

'serial'はバックグラウンドでシーケンスを使用します。本質的に違いはありません。あなたの挿入の直後に 'lastval()'を使うことはどちらの場合でもうまくいきます。 –

+0

助けてくれてありがとう –

答えて

18

Sequence vs. Serial

シーケンスがちょうどユニークな数のシーケンスを作成します素敵な答えをチェックしてください。これはデータ型ではありません。それはシーケンスです。例えば:あなたはこのような複数の場所で同じシーケンスを使用することができます

create sequence testing1; 
select nextval('testing1'); -- 1 
select nextval('testing1'); -- 2 

create sequence testing1; 
create table table1(id int not null default nextval('testing1'), firstname varchar(20)); 
create table table2(id int not null default nextval('testing1'), firstname varchar(20)); 

insert into table1 (firstname) values ('tom'), ('henry'); 
insert into table2 (firstname) values ('tom'), ('henry'); 

select * from table1; 

| id | firstname | 
|----|-----------| 
| 1 |  tom | 
| 2 |  henry | 

select * from table2; 

| id | firstname | 
|----|-----------| 
| 3 |  tom | 
| 4 |  henry | 

シリアルは、疑似データ型です。シーケンスオブジェクトを作成します。ストレートフォワードテーブル(リンクに表示されるものに似ています)を見てみましょう。

create table test(field1 serial); 

これにより、テーブルとともにシーケンスが作成されます。シーケンス名の命名法は__seqです。上記1が相当である:

create sequence test_field1_seq; 
create table test(field1 int not null default nextval('test_field1_seq')); 

も参照してください:http://www.postgresql.org/docs/9.3/static/datatype-numeric.html

あなたが自動作成されたシリアルデータ型である配列を再利用することができ、またはあなただけのテーブルごとに1つのシリアル/シーケンスを使用することもできます。

create table table3(id serial, firstname varchar(20)); 
create table table4(id int not null default nextval('table3_id_seq'), firstname varchar(20)); 

テーブル表5(IDシリアル、FIRSTNAMEのVARCHAR(20))を作成します(ここではリスクは表3が削除され、我々は表3のシーケンスを使用し続けた場合、我々はエラーになりますということです)。

insert into table3 (firstname) values ('tom'), ('henry'); 
insert into table4 (firstname) values ('tom'), ('henry'); 
insert into table5 (firstname) values ('tom'), ('henry'); 

select * from table3; 
| id | firstname | 
|----|-----------| 
| 1 |  tom | 
| 2 |  henry | 

select * from table4; -- this uses sequence created in table3 
| id | firstname | 
|----|-----------| 
| 3 |  tom | 
| 4 |  henry | 

select * from table5; 
| id | firstname | 
|----|-----------| 
| 1 |  tom | 
| 2 |  henry |  

例を試してみるお気軽に:http://sqlfiddle.com/#!15/074ac/1

+4

はい、しかし、 'シリアル'は実際のデータ型ではありません。これは疑似データ型です。これは重要な違いです。http://stackoverflow.com/a/27309311/939860またはhttp:///stackoverflow.com/a/14651788/939860そして、特別な状況でシーケンスを共有することは意味があります。このような場合は、シリアル列で 'OWNED 'でないものを使用することになります。答えの一番下に記載されている注意点を避けてください。 –