Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

postgresql - Implementing get or create function

I need to create a function in PostgreSQL using the pl/pgSQL language. I have the following four tables:

CREATE TABLE person (
     id serial PRIMARY KEY,
     name text NOT NULL,
     town_id integer NOT NULL,
     country_id integer NOT NULL,
     FOREIGN KEY (town_id) references towns (id),
     FOREIGN KEY (country_id) references countries (id)
);

CREATE TABLE towns (
    id serial PRIMARY KEY,
    name text UNIQUE NOT NULL
);

CREATE TABLE countries (
    id serial PRIMARY KEY,
    name text UNIQUE NOT NULL
);

Now I want to create a function that receives a person record and normalizes this into these tables. The example record is:

 name: Jakob
 town: Los Angeles
 country: USA

In other words, I want to store unique town names in the table towns, and I want to store unique county names in the table countries. I would thus like to implement a "get-or-create" that checks whether a value already exists, and if yes, fetch the primary key. Otherwise, I want to insert the town/country based on the provided name, and fetch the id. Then insert this in the person table.

How would this work as a function in the pl/pgSQL language?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...