简体   繁体   中英

INSERT MULTIPLE ROWS in Gerund Table using Insert Into Select

I used INSERT INTO SELECT to copy values (multiple rows) from one table to another. Now, my problem is how do I insert rows with its corresponding IDs from different tables (since it's normalized) into a gerund table because it only outputs one row in my gerund table. What should I do to insert multiple rows and their corresponding IDs in the gerund table.

My code for the gerund table goes like this.

$insert = "INSERT INTO table1 SELECT * FROM sourcetable"; // where id1 is pk of table1.


$result =mysqli_query($conn,$insert)
$id1=mysqli_insert_id($conn);

Now table 1 has inserted multiple rows same as the other 2 tables.

Assuming id.. are the foreign keys

INSERT INTO gerundtable (pk, id1,id2,id3) VALUES ($id1,$id2,$id3);

My problem is it doesn't yield multiple rows.

According to MySql documentation :

For a multiple-row insert, LAST_INSERT_ID() and mysql_insert_id() actually return the AUTO_INCREMENT key from the first of the inserted rows. This enables multiple-row inserts to be reproduced correctly on other servers in a replication setup.

So, grab the number of records being copied, and the LAST_INSERT_ID() and you should be able to map exact IDs with each copied row.

In the lines of:

$mysqli->query("Insert Into dest_table Select * from source_table");

$n = $mysqli->affected_rows; // number of copied rows

$id1 =  $mysqli->insert_id; // new ID of the first copied row
$id2 = $mysqli->insert_id + 1; // new ID of the second copied row
$id3 = $mysqli->insert_id + 2; // new ID of the third copied row
...

$mysqli->query("INSERT INTO gerundtable (pk, id1,id2,id3) VALUES ($id1,$id2,$id3)");

Thank you for trying to understand and also answering my question. I resolved my own code. I used while loop to get the ids of every row and didn't use INSERT INTO SELECT. Here is the run down. SInce I'm just using my phone bare with my way posting.

 $sqlselect = SELECT * FROM table1;
While($row=mysqli_fetch_array(table1){
    $insertquery...
    $id1=mysqli_insert_id($conn)

    $insertgerundtable = INSERT INTO gerundtable VALUES ( $id1, $id2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM