开发者

Inserting 2 rows, each to different tables where one row refrences the other's primary key

开发者 https://www.devze.com 2023-02-05 17:13 出处:网络
Hello folks Checkout this scenario Table 1 columns -> | table_1_id (pkey) | some_column | comments | Table 2 columns -> | table_2_id (pkey) | some_other_column | table_1_id (fkey) | comments |

Hello folks Checkout this scenario

Table 1 columns -> | table_1_id (pkey) | some_column | comments |

Table 2 columns -> | table_2_id (pkey) | some_other_column | table_1_id (fkey) | comments |

All primary keys are of type serial or auto number. The 3rd column on Table 2 is an fk that references Table 1's primary key.

I would like to insert rows into both programmaticaly (from a c++ app)

Do i have to insert to table one then SELECT-query the entry's primary key then insert the Table 2 row with the pkey result?

Is there开发者_Python百科 a more efficient way of handling this? Say using almost 2 queries?


I would suggest looking http://wiki.postgresql.org/wiki/FAQ

The site is a useful resource to go through to get familiar with PostgreSQL

Specifically, the section How do I get the value of a SERIAL insert?

The simplest way is to retrieve the assigned SERIAL value with RETURNING. Using the example table in the previous question, it would look like this:

INSERT INTO person (name) VALUES ('Blaise Pascal') RETURNING id;

You can also call nextval() and use that value in the INSERT, or call currval() after the INSERT.


If you don't need the table_1_id value in your application, you can skip retrieving it completely:

INSERT INTO table_1(cols...) VALUES(vals...)
INSERT INTO table_2(table_1_id, cols...) VALUES(currval('table_1_table_1_id_seq'), vals...)
0

精彩评论

暂无评论...
验证码 换一张
取 消