T
T
Tenebrius2015-05-27 18:21:22
MySQL
Tenebrius, 2015-05-27 18:21:22

How to correctly add data to related tables?

There are 2 tables - tbl_1 and tbl_2.
The tbl_2.parent_id field points to (equals to) the tbl_1.id field.
3f3eae0bdf294e94bc776b7f7ae778a3.png
Those. table data is linked.
The question itself: how to insert data into both tables at once, if I cannot know the id of the parent record until I insert it?
So far the algorithm is:

  • Insert data into first table
  • Get the id of the first table (SELECT id FROM tbl_1 WHERE string='$string')
  • Knowing parent id to interpose the data into the second table.

Here it turns out for an insertion of 2 lines 3 requests are fulfilled. In fact, I have five tables, and each, except for the first, must know the id of the ancestor. And the number of requests in my opinion is great. Is there a way to optimize this process?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Makarov, 2015-05-27
@Tenebrius


https : //dev.mysql.com/doc/refman/5.0/en/getting-un... .
I draw your attention to the fact that this variable is stored at the connection level, that this is not a request - there will be no search, just a request for a value from the server's memory.

U
urmi tilek uulu, 2015-05-28
@urma

Your algorithm:
I think is right. If this is WEB programming, then the data from the first table can be put in <select>together with the ID and added.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question