将记录数分成组?

时间:2012-01-25 19:24:24

标签: php

我在CSV文件中有大量记录。

我正在尝试将多个Insert实现为单个查询,但我需要根据Total记录来训练我需要多少单个查询。

例如:

$totalRecord = 1620;

所以我需要17个查询。 16个查询将有100个Insert记录,第17个查询将有20个记录。

$totalRecord的数量可以介于1到500,00之间

如何解决这个问题?

例如:

Query 1:
INSERT INTO [table] 
( [field1], [field2], [field3] ) VALUES 
( '[value1.1]', '[value1.2]', '[value1.3]' ), 
( '[value2.1]', '[value2.2]', '[value2.3]' ), 
( '[value3.1]', '[value3.2]', '[value3.3]' ),

Query 2: 
INSERT INTO [table] 
( [field1], [field2], [field3] ) VALUES 
( '[value1.1]', '[value1.2]', '[value1.3]' ), 
( '[value2.1]', '[value2.2]', '[value2.3]' ), 
( '[value3.1]', '[value3.2]', '[value3.3]' ),

3 个答案:

答案 0 :(得分:2)

使用模数和除法:

$recordsineachquery = 100;
$recordsinlastquery = $totalrecords % $recordsineachquery;
$fullqueries = ($totalrecords - $recordsinlastquery) / $recordsineachquery;
$totalqueries = $fullqueries + 1;

答案 1 :(得分:0)

使用整数除法查找组数和模数运算符,以找出最后一组中的插入数:

// You have to round the division result because PHP doesn't do integer division.
$numGroups = (int)($totalRecords / 100);
$remainder = $totalRecords % 100;

答案 2 :(得分:0)

您可以这样做:

$batchProcessLimit = 100;
$batchStep = 0;

$query = "INSERT INTO [table] ( [field1], [field2], [field3] ) VALUES ";

foreach($rows as $row)
{
    $query .= "( '[value1.1]', '[value1.2]', '[value1.3]' )"

    if ($batchProcessLimit % ++$batchStep != 0) $query .= ",";
    else
    {
        // execute the query

        $query = "INSERT INTO [table] ( [field1], [field2], [field3] ) VALUES ";
    }
}

// execute the query for remaining rows