I have 2 tables, one is parent and another one is child. Parent table has a field called "parent_id" (primary key) and child table has a field called "parent_id"(foreign key) so there are link together. If I insert a row into the parent table and at same time I also want to insert a row into child table with the same parent id in the parent_id field. How to do this?
Asked
Active
Viewed 2,817 times
3
-
Is `parent.parent_id` an auto increment field? – Barmar Mar 07 '13 at 06:16
-
possible duplicate of [Mysql insert into 2 tables](http://stackoverflow.com/questions/3053593/mysql-insert-into-2-tables) – Barmar Mar 07 '13 at 06:17
-
If there is a foreign key constraint established, before inserting an entry into child table you have to make sure that the corresponding parent entry exists in the parent table. If you don't have a parent entry, and still trying to insert a child entry, what's the point in having a foreign key constraint, right? – Amith Koujalgi Mar 07 '13 at 06:18
-
If you want to insert an entry into a child table which has a foreign key to parent table's entry, within a single statement, you can write a stored procedure and call that procedure when you would wish to insert the entries. – Amith Koujalgi Mar 07 '13 at 06:21
1 Answers
0
You need to write a stored procedure. http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html

Doc Kodam
- 723
- 6
- 14