Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert Data Into Tables Linked by Foreign Key

Tags:

sql

postgresql

I am using PostgreSQL.

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?

like image 789
Cheok Yan Cheng Avatar asked Jan 04 '10 07:01

Cheok Yan Cheng


People also ask

Can a foreign key reference a table?

InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are the first columns in the same order. Hidden columns that InnoDB adds to an index are also considered (see Section 15.6.

Can I add a foreign key constraint to an existing table with data?

We can add a FOREIGN KEY constraint to a column of an existing MySQL table with the help of ALTER TABLE statement.

How do you reference a foreign key to multiple tables?

This is sometimes also called as a referencing key. A Foreign Key is a column or a combination of columns whose values match a Primary Key in a different table. The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key in the second table.


1 Answers

You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:

insert into "order" (customer_id, price) values \ ((select customer_id from customer where name = 'John'), 12.34); 

If the customer does not exist, you'll get an sql exception which text will be something like:

null value in column "customer_id" violates not-null constraint 

(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:

insert into customer(name) values ('John'); insert into "order" (customer_id, price) values \ ((select customer_id from customer where name = 'John'), 12.34); 

Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.

like image 56
Wayne Conrad Avatar answered Sep 24 '22 08:09

Wayne Conrad