'How do I add to a table and then use the id for a different query?

I have three tables, which I create with these queries:

create table parents(
    rowid serial primary key,
    display_name varchar,
    unique(display_name)
);

create table clients(
    rowid serial primary key,
    parent int,
    display_name varchar,
    foreign key (parent) references parents(rowid),
    unique(display_name, parent)
);

create table datapoints(
    rowid serial primary key,
    client int,
    val float8,
    foreign key (client) references clients(rowid)
);

I am getting data which contains parent name, client name and some value. Each time I get this data, I want to add rows to the datapoints table. I also want to add rows to the clients and parents table, but only if the data I received has unrecognized names.

For example, I might get this data:

"parent1-client1-123.0"

What I would like to achieve is to process this data (in a query), this way:

Insert a row to the "parents" table, if needed.

Insert a row to the "clients" table with the appropriate parent id (obtained in the previous step?), if needed.

Insert a row to the "datapoints" table with the appropriate client id (obtained in the previous step?).

How can I manage this with queries? The programmer in me wants to write:

  • Insert into parents if needed. Save the id of appropriate parent in a variable "current_parent"
  • Insert into clients if needed, using the "current_parent" variable. Save the id of the appropriate client in a variable "current_client".
  • Insert into datapoints, using the "current_client" variable from the prev. step.

But obviously this is not how sql works, right? And what if, instead of these three "nested" tables I have 5, or 10?(!)

Please help



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source