Mircea Badescu
Mircea Badescu

Reputation: 301

SQL Before Insert Trigger - insert into another table and update foreign key

I have two tables: car and engine. Each car has one engine so the car table has an engineID field which is a foreign key pointing to the id field on the engine table.

Now what i want to do is before inserting a new car, I want to create a new engine entry with null values and then insert the id of the newly created engine into the engineID field of the car entry.

Is there any way I can achieve that using triggers? I'm using MySQL.

Upvotes: 0

Views: 642

Answers (1)

fancyPants
fancyPants

Reputation: 51888

I don't understand why you want to have rows with all null values in your table, but you're on the right track, that you first have to create the engine (or look it up).

Your engine table should have an auto_increment column. Then you check, wether a proper entry already exists. If yes, get the id number. If not, insert it (or create a new row by inserting just null). You can get the id that was generated by querying LAST_INSERT_ID(). Then you use this id in your car table.

Don't do this in a trigger, but use transactions.

Upvotes: 1

Related Questions