简体   繁体   English

使用插入选择在动名词表中插入多行

[英]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.我使用 INSERT INTO SELECT 将值(多行)从一个表复制到另一个表。 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.现在,我的问题是如何将来自不同表的具有相应 ID 的行(因为它已规范化)插入到动名词表中,因为它只在我的动名词表中输出一行。 What should I do to insert multiple rows and their corresponding IDs in the gerund table.我应该怎么做才能在动名词表中插入多行及其对应的 ID。

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.现在表 1 插入了与其他 2 个表相同的多行。

Assuming id.. are the foreign keys假设 id.. 是外键

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

My problem is it doesn't yield multiple rows.我的问题是它不会产生多行。

According to MySql documentation :根据MySql 文档

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.对于多行插入,LAST_INSERT_ID() 和 mysql_insert_id() 实际上从插入的第一行返回 AUTO_INCREMENT 键。 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.因此,获取正在复制的记录数和LAST_INSERT_ID() ,您应该能够为每个复制的行映射精确的IDs

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.我使用 while 循环来获取每一行的 id,并没有使用 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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