[英]Best way to merge and store multiple csv file using mysql and php
我正在与一家公司合作,每天都会给我一个大约25.000行的CSV
文件。 一天的CSV
与前一天的CSV
之间的差异在于,在最新的一行中,删除了一些行(少于总数)并且添加了其他行。 因此这两个文件共有大约24900行。
我必须在时间中存储所有行..所以每天我都要使用当前的CSV更新我在DB中的表。
我想想:
<?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..
}
}
?>
我认为这不是非常强大和快速。 有没有更好的方法? 谢谢!!!
在id
字段上创建唯一索引(也许你已经完成)并使用INSERT IGNORE
或INSERT ... ON DUPLICATE KEY UPDATE
ALTER TABLE table_where_i_store_all ADD UNIQUE(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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.