简体   繁体   English

php mysql选择在同一服务器上的不同DB上插入

[英]php mysql select insert on different DBs in same server

I have two DBs on the same server. 我在同一台服务器上有两个DB。 Table1 in db1 has 11 columns, and around 8 million rows of data. db1中的table1有11列,大约有800万行数据。 I want to insert four columns' worth of table1 data (ie, 4 columns x 8 million rows) into table2 in db2. 我想在db2中的table2中插入四列值为table1的数据(即4列x 800万行)。

I tried this using php in the script below, first selecting everything in db1.table1 then inserting the results inside a while loop. 我在下面的脚本中尝试使用php,首先在db1.table1中选择所有内容,然后将结果插入while循环中。

But -- based on an experiment to insert 10,000 rows (which took 7 minutes) I think it will take 12 hours to put all 8 million rows into db2.table2. 但是 - 基于插入10,000行(需要7分钟)的实验,我认为将所有800万行放入db2.table2需要12个小时。 My approach appears extremely inefficient, but have a look: 我的方法效率极低,但看看:

<?php

   ///////////  set up connections to db1 and db1
$link = new mysqli('localhost', 'root', '', 'db1');

/////////// query to get data from db1/table1 
$sql1 = "select * from db1.table1";
$sql1_result = mysqli_query($link, $sql1) or die ("sql1 failed: " . mysqli_error());

/////////// turn data from db1.table1 into php variables
        while ( $row = mysqli_fetch_assoc($sql1_result))
    {   
            extract($row);// gives 8 million rows, each containing 11 pieces of data

/////////// connect to database db2 
$link->select_db('db2');

/////////// put query results into db2
$sql2 = "insert ignore into db2.table2  (field4, field5, field6, field7)
values ('$field4', '$field5', '$field6', '$field7')";
$sql2_result = mysqli_query($link, $sql2) or die ("sql2 failed: " . mysqli_error()); 
}
?>

After researching, I wonder if doing an INSERT INTO SELECT would be faster and more efficient, but I can't figure out how to handle the two db connections. 经过研究,我想知道INSERT INTO SELECT是否会更快更有效,但我无法弄清楚如何处理这两个数据库连接。

Any ideas? 有任何想法吗?

If your connection has rights to both databases, there is no need to have two connections. 如果您的连接具有两个数据库的权限,则无需具有两个连接。 A database connection is a connection to the server, not to a specific database (although you can select a default database within the connection). 数据库连接是与服务器的连接,而不是与特定数据库的连接(尽管您可以在连接中选择默认数据库)。

What you can do is normal INSERT INTO SELECT within one connection: 您可以做的是在一个连接中正常INSERT INTO SELECT:

insert ignore into db2.table2  (field4, field5, field6, field7)
select field4, field5, field6, field7
from db1.table1;

This way the execution is done in the database server, without need to move the data to PHP (and back). 这样,执行在数据库服务器中完成,无需将数据移动到PHP(并返回)。

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

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