Вопрос

Here is the scenario: I have 2 tables and 2 temporary tables. Before I insert user data to the official tables, I insert them to a temp table to let them do the checks. There is a company table with company info, and a contact table that has contact info. The contact table has a field called company_id which is a foreign key index for the company table.

Temp tables are set up the same way.

I want to do something like: INSERT INTO company () SELECT * FROM temp_company; and INSERT INTO contact () SELECT * FROM temp_contact

My question is, how do I transfer the foreign key from the temp_company to the newly inserted id on the company table using a statement like this? Is there a way to do it?

Currently I am:

  1. grabbing the temp rows
  2. going one by one and inserting them
  3. grabbing the last insert id
  4. then inserting the contacts afterwards with the new last insert id

I just don't know if that is the most efficient way. Thanks!

Это было полезно?

Решение

if you have the same number of columns in both tables and then you should just be able to use the syntax you have there? Just take out the (). Just make sure there aren't any duplicate primary keys:

INSERT INTO company SELECT * FROM temp_company;
INSERT INTO contact SELECT * FROM temp_contact;

You can also specifically specify the columns that get inserted, this way you can specify exactly which column you insert as the new ID.

INSERT INTO company (`ID`,`col_1`,...,`last_col`) SELECT `foreign_key_col`,`col_1`,...,`last_col` FROM temp_company;
INSERT INTO contact (`ID`,`col_1`,...,`last_col`) SELECT `foreign_key_col`,`col_1`,...,`last_col` FROM temp_contact;

Just make sure you are selecting the right # of columns.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top