Partenza una risposta piacevole circa Sequence vs. Serial
Sequence sarà solo creare sequenza di numeri unici. Non è un tipo di dati. È una sequenza. Per esempio:
create sequence testing1;
select nextval('testing1'); -- 1
select nextval('testing1'); -- 2
è possibile utilizzare la stessa sequenza in più posti come questo:
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 |
seriale è uno pseudo tipo di dati. Creerà l'oggetto sequenza. Diamo un'occhiata a un tavolo straight-forward (simile a quello che vedrai nel link).
create table test(field1 serial);
Ciò causerà la creazione di una sequenza insieme alla tabella. La nomenclatura del nome della sequenza è __seq. Quanto sopra uno è equivalente di:
create sequence test_field1_seq;
create table test(field1 int not null default nextval('test_field1_seq'));
Vedi anche: http://www.postgresql.org/docs/9.3/static/datatype-numeric.html
È possibile riutilizzare la sequenza che è auto-creato da tipo di dati di serie, oppure si può scegliere di utilizzare solo uno di serie/sequenza per tabella.
create table table3(id serial, firstname varchar(20));
create table table4(id int not null default nextval('table3_id_seq'), firstname varchar(20));
(Il rischio qui è che se table3 è caduto e noi continuare a utilizzare la sequenza di table3, otterremo un errore) create table table5 (id di serie, nome varchar (20));
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 |
Sentitevi liberi di provare un esempio: http://sqlfiddle.com/#!15/074ac/1
Se si desidera la sua sequenza seriale o assegnato a quello che hai appena inserito, è meglio usare il 'dichiarazione RETURNING'''' '. Vedi http://stackoverflow.com/questions/19167349/postgresql-insert-from-select-returning-id –
Un 'seriale' utilizza una sequenza in background. Non c'è essenzialmente alcuna differenza. L'uso di 'lastval()' subito dopo l'inserimento va bene in entrambi i casi. –
grazie per l'aiuto –