Insert Data Into Tables Linked by Foreign Key

From: Yan Cheng Cheok <yccheok(at)yahoo(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Insert Data Into Tables Linked by Foreign Key
Date: 2010-01-04 08:53:39
Message-ID: 189510.64322.qm@web65702.mail.ac4.yahoo.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Customer
==================
Customer_ID | Name

Order
==============================
Order_ID | Customer_ID | Price

To insert an order, here is what I need to do usually,

For example, "John" place "1.34" priced order.

(1) Get Customer_ID from Customer table, where name is "John"
(2) If there are no Customer_ID returned (There is no John), insert "John"
(3) Get Customer_ID from Customer table, where name is "John"
(4) Insert "Customer_ID" and "1.34" into Order table.

There are 4 SQL communication with database involved for this simple operation!!!

Is there any better way, which can be achievable using 1 SQL statement?

Thanks and Regards
Yan Cheng CHEOK

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Thomas Kellerer 2010-01-04 10:20:02 8.5 Alpha3 - broken downloadlink
Previous Message Chris Withers 2010-01-04 08:43:01 how do I disable automatic start on mac os x?