我在一家公司工作,这家公司每天给我一个大约25.000行的CSV文件。一天的CSV与前一天的不同之处在于,在最新的一天中,删除了一些行(比总数少得多),而增加了其他行。因此,这两个文件大约有24900行是相同的。
我必须存储时间中的所有行。因此,我每天都要用当前的CSV更新数据库中的表。
我在想:
<?php
$fh = fopen($actual_csv, 'r');
$contents = fread($fh, filesize($actual_csv));
fclose($fh);
$fileLines = explode("\n", $contents);
for ($i = 1; $i < count($fileLines) - 1; $i++) {
$fieldList = explode(';', $fileLines[$i]);
//$fieldList[0] is my unique id
if(mysql_num_rows(mysql_query("SELECT * FROM table_where_i_store_all WHERE id='$fieldList[0]'"))<=0){
mysql_query("INSERT INTO table_where_i_store_all (column names..) VALUES ('$fieldList[0],........')"); // there are many column so i don't write it..
}
}
?>我认为这不是非常强大和快速。有没有更好的办法?谢谢!
发布于 2012-09-19 21:04:34
ALTER TABLE table_where_i_store_all添加唯一( id );
$fileLines = explode("\n", $contents);
$linemax = count( $fileLines )-1;
if( $linemax < 1 ) // empty file?
return;
$SQL = "INSERT IGNORE INTO table_where_i_store_all (column_names) VALUES ";
for ($i = 1; $i < $linemax; $i++) {
$fieldList = explode(';', $fileLines[$i]);
//$fieldList[0] is my unique id
$SQL .= "('$fieldList[0],........'),";
}
$SQL = substr( $SQL, 0, strlen($SQL)-1); // remove extra comma from end
$res = mysql_query($SQL);发布于 2012-09-19 16:20:42
在id字段上创建唯一索引(可能您已经在中这样做了)并使用INSERT IGNORE或INSERT ... ON DUPLICATE KEY UPDATE
https://stackoverflow.com/questions/12490857
复制相似问题