从 MYSQL DATABASE_1 中选择所有
几乎每个项目编辑(拆分、合并、验证电子邮件格式、验证 URL 格式等)的最佳方法是什么 - 通过使用 php,然后使用 插入
新数据库2
。
旧表有近 300 万行。
如果我对每一行执行foreach(这不是一个好主意:)),则 2000 行需要超过 1 小时。
如果我在一个查询中插入多行:
INSERT INTO tbl (col1, col2, ...) VALUES (item1, item2, ...), (item3, item4, ...)
几乎一样
有什么想法可以专业且快速地做到这一点吗?
最佳答案
您可以对查询进行分页并使用多个 php 进程。例如,一个进程检索并编辑 100000 个元素,然后将其插入到新数据库中。
要实现它,您可以创建一个 php 父进程,将工作负载分配到子进程中,如下所示:
$total_rows = //Get from your mysql table
$offsets = []
$limit = 10000;
//Create offsets to process in bulk
for ($i=0 ; $i<$total_rows ; $i++) {
$offsets[] = ($i * limit);
}
//Process rows
while ($processed_rows < $total_rows)
$pids = [];
//Create 10 childs processes
for ($i=0;$i<10;$i++) {
if ($pid) {
$pids[] = $pid;
} else {
//Get next offset to process
$offset = array_shift ($offsets);
process_and_insert_row($offset, $limit); //this function gets, edits and inserts items
}
}
//Wait for childs to finish
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
$processed_rows += $limit;
unset($pids[$pid]);
}
}
警告:代码未经测试,但我认为它演示了解释背后的想法...
关于php - 选择、编辑数据,然后将数据插入新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41046758/