简体   繁体   English

PHP Foreach大数据

[英]PHP Foreach large data

There is MySQL table with 24500 rows of data, and there is text file with 26000 string of data needed to be inserted into MySQL, problem is what this 26000 strings duplicates data in MySQL table, so we need to compare them, and insert only new/unique. 有一个具有24500行数据的MySQL表,还有一个文本文件,需要将26000字符串数据插入MySQL,问题是这26000字符串与MySQL表中的数据重复,因此我们需要对其进行比较,并仅插入新的/独特。

cadastreArray - array from text file cadastreArray-文本文件中的数组

districtArray - mysql array districtArray -MySQL数组

When i try to do 当我尝试去做

foreach ($cadastreArray as $cadastreValue) {
    $districtExist = false;
    foreach ($districtArray as $districtData) {
        if ($cadastreValue[0] == $districtData['1']) {
            $districtExist = true;
            break;
        }
    }
}

if(!$districtExist) { MySQL INSERT ... }

i am getting execution time error, and even 3 minutes are not enought. 我收到执行时间错误,甚至3分钟也不够。 Maybe you can offer better/faster way? 也许您可以提供更好/更快的方法?

May be you can set the mysql field as unique so when you will be going to insert it will not insert and will generate error number and will continue execution. 可能是您可以将mysql字段设置为唯一字段,因此当您要插入mysql字段时,它将不会插入,并且会生成错误号并继续执行。 So you need not to compare. 因此,您无需进行比较。

One more thing that you can do is you can increase max_execution_time in php.ini 您可以做的另一件事是可以在php.ini中增加max_execution_time

Another option. 另外一个选项。 Load your 26k text file into a temp table (LOAD DATA INFILE... will do this quickly). 将您的26k文本文件加载到临时表中(LOAD DATA INFILE ...将很快完成此操作)。

Then you can do an insert based on a query that takes your temp table and LEFT JOINs that against your full table, checking that a field on the full table is NULL. 然后,您可以基于一个查询来进行插入,该查询采用您的临时表和针对整个表的LEFT JOIN,并检查整个表上的字段为NULL。

Simple example script here:- 简单的示例脚本在这里:

<?php

$file = "SomeTextFile.txt";

$sql = "CREATE TEMPORARY TABLE cadastre
(
    field1 INT,
    field2 VARCHAR(255),
    etc...
)";

if(!($db->query($sql)))
{
    die($db->error());// if error, stop script
}

if(!($db->query("LOAD DATA INFILE '$file' INTO TABLE cadastre")))
{
    die($db->error());// if error, stop script
}

$sql = "INSERT INTO district (field1, field2, field3, ......)
        SELECT a.field1, a.field2, a.field3
        FROM cadastre a
        LEFT OUTER JOIN district b
        ON a.field1 = b.field1
        WHERE b.field1 IS NULL";

if(!($db->query($sql)))
{
    die($db->error());// if error, stop script
}

?>

Make sure the temp table and the table you are inserting into have useful indexes added. 确保临时表和要插入的表已添加有用的索引。

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

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