【问题标题】:Select, edit and then insert data into new database选择、编辑然后将数据插入新数据库
【发布时间】:2016-12-08 18:51:38
【问题描述】:

SELECT all from MYSQL DATABASE_1 几乎每个项目编辑(拆分、合并、验证电子邮件格式、验证 URL 格式等)的最佳方法是什么 - 使用 php,然后使用 INSERT INTO new DATABASE 2

旧表有近 300 万行。

如果我为每一行执行 foreach(这不是一个好主意 :))2000 行需要超过 1 小时。

如果我在一个查询中插入多行:

    INSERT INTO tbl (col1, col2, ...) VALUES (item1, item2, ...), (item3, item4, ...)

几乎一样

任何想法如何专业和快速地做到这一点?

【问题讨论】:

  • 因为我几乎要编辑每个项目。正如我所说,验证,替换某些东西,拆分某些东西。这是未经验证的输入的垃圾。
  • mysql - 写在帖子的第一行;)

标签: php mysql sql performance insert


【解决方案1】:

您可以对查询进行分页并使用多个 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]);
    }
}

警告:代码未经测试,但我认为它展示了解释背后的想法......

【讨论】:

  • 这似乎合乎逻辑。我要试试。谢谢。
  • 一次只做 1000 个——否则你可能会在 PHP 中耗尽内存。 More discussion 分块。
猜你喜欢
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-22
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多