Inserting self-referential records in Postgresql -


Looking at the following table in PostgreSQL, how can I include a record that refers to itself?

  

Code> Prepare the table (id's serial primary key, name is VARCHAR (255), parent_id is not drawn, foreign key (parent_id) reference reference (id) );

Examples are being given on the web, paren_id has been allowed to tap and then the trigger has been used to update it. If possible, I can update in one shot.

You can select last_value from the sequence, when you use Type Serial Forms:

  table test (id serial primary key, parental integer tap, foreign key (parent) reference test (id)); Enter into test values ​​(default, (choose last_file_type from test_id_seq)); Enter into test values ​​(default, (choose last_file_type from test_id_seq)); Enter into test values ​​(default, (choose last_file_type from test_id_seq)); Choose * from the exam; ID | Parents ---- + -------- 1 | 1 2 | 2 3 | 3 (3 rows)  

And the following also seem to be simple: also work in the

  test values ​​(default, last ());  

Although I do not know how this will work when using multiple sequences ... I saw it; The last (final) value has been returned or set to any sequence with the final sequence or set call, so the following will bring you in trouble:

  table test (id serial primary key, Foo serial faucet, parental integer tap, foreign key (parent) references reference (ID)); Choose Settle ('test_foo_seq', 100); Insert test values ​​(default, default, last ()); Error: Enter or update on table "test" violation of foreign key constraint "test_parent_fkey" extension: key (guardian) = (101) table is not present in "test"  

Although the following Will be fine:

  Insert test values ​​(default, default, currval ('test_id_seq')); Choose * from the exam; ID | Foo | Parents ---- + ----- + -------- 2 | 102 | 2 (1 line)  

Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -