简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM