Hey. I will try to briefly retell my task, which I cannot solve due to lack of experience.

Imagine that you have a certain table1 with group names (id, group_name, element_name_id) that refers to the id of the element of table2 (id, element_name), and both of them are empty. So this primitive link is built. id - AI.

Suppose: I need to add for one or several requests the fields Smartphone and iPhone, entered by the user. But the fact is that the team needs to know the id from the table of elements in the field element_name_id, which would have to be inserted first, otherwise there will be no matching. In short, it is over this that I break my head, and do not even know what to ask in Google. Obviously, this is an INSERT. It is necessary that in table1 I saw: name: smartphone, element_id -> 0 IPhone.

I work in phpmyadmin and HeidiSQL.

  • I do it like this: When a user enters data into tables that are related to others, I create automatically related tables and pass the last id from them, which I link to the main one. But, just like you, I don’t know if this is right - Ep1demic

1 answer 1

No need to think things out, think arrays. With the first INSERT .. VALUES query, enter all the data in the table on the "one" side. And the second - in the table on the side of the "many" query INSERT .. SELECT. In this case, the data source of the SELECT clause is the first table from which you, using the data just entered, obtain the IDs required for the link for insertion into the second table. The simplest example is:

INSERT INTO `table1` (`name`) VALUES ('Яблоки'); INSERT INTO `table2` (`table1_id`, `color`) SELECT t1.ID, 'зелёные' FROM `table1` t1 WHERE t1.`name` = 'Яблоки'; 
  • Ps. Although in the example is entered by one value, nothing prevents to bring them immediately packs. Although, as for me, it is better to first bring them as they are in a temporary one, and from there parse with requests to work tables. - Akina