randomuser2
randomuser2

Reputation: 105

The order of inserting data to two (or more) tables in mysql database

I want to insert data to my database, however there are tables that are dependent on each other, for example:

table1:

table1_id (PK, unique)  |  some_text  |  table2_id (FK, unique in table2)

table2:

table2_id (PK, unique)  |  table1_id (FK, unique in table2)  |  table3_id (FK, unique in table3)

table3:

table3_id (PK, unique)  |  table1_id (FK, unique in table1)  | some_other_data

and let's say this tables are related to e.g. commercial, so in table one we store the information about commercial, in table2 about the client and in table3 about the planned_plays of each commercial. So when I want to create a new commercial - I need to fill all 3 tables at once. But the problem is that for example - while creating table1 I need to know the table2_id (which I didn't create at this point yet), etc. How can I fix it?

Upvotes: 2

Views: 73

Answers (2)

Vishal
Vishal

Reputation: 211

It would be better if DB design changed slightly, FK's in all tables referring one another would be difficulty or complex to insert data.

So below schema may help you!

Table 1
table1_id (PK)       |      some_other_columns

Table 2
table2_id (PK)    |     table1_id (FK, unique in table2)

Table 3
table3_id (PK)       |       table1_id (FK referring table 1)     |    table2_id(FK referring table 2)

Start inserting from table1 to table3 in sequence

Upvotes: 2

Mohammad
Mohammad

Reputation: 3547

Simply insert the table1 data and let the table2_id (FK) is empty or 0.

Then insert the table3 data, now you have tabl1_id & table3_id, so you can insert the data of table2.

Finally when the row has been added successfully to the table2, you can update table1 to change the table2_id from (null or 0) to the real table2_id.

Upvotes: 2

Related Questions