需求是 上传Excel 读取里面的数据。根据Excel中某一个字段,与数据表中的一个字段的唯一性。然后把 Excel表中数据和数据库表中数据一次更改。本次测试一次更新31条数据。 本次测试基于帝国cms
方法1 用一个for徐循环把读取的数据放在一个数组中然后在十几万条的数据表中逐条查询更改,用时35s;
$numArr = count($arr);
$m = ceil($numArr/10000);
for($i=1;$i<=$numArr;$i++){
$n = $i*10000;
$j = $n-10000;
for($q=$j;$q<$n;$q++){
$res = $empire->query("update {$dbtbpre}enewsclass set bname=‘".$arr[$i][1]."‘,classpagekey=‘".$arr[$i][2]."‘,intro=‘".$arr[$i][3]."‘ where classpath=‘".$arr[$i][i]."‘");
if($res){
echo "更新成功!路径信息为:".$arr[$i][0];
}
}
}
方法 二;创建临时表。用时23s
$sqls ="DROP TABLE IF EXISTS `linshitbale`;\n";
$sqls .="create Temporary table linshitbale (id int(11) primary key auto_increment,classpath varchar(255),bname varchar(255),intro varchar(255),classpagekey varchar(255));\n";
$bsql ="";
foreach ($arr as $k => $v) {
$k+=1;
$bsql .="(".$k.",‘".$v[0]."‘,‘".$v[1]."‘,‘".$v[3]."‘,‘".$v[2]."‘),";
}
$bsql = trim($bsql,",");
$sqls .= "insert into linshitbale values ".$bsql.";\n";
$sqls .= "update {$dbtbpre}enewsclass as c,linshitbale as ls set c.bname=ls.bname,c.intro=ls.intro,c.classpagekey=ls.classpagekey where c.classpath = ls.classpath;";
echo $sqls;
第三种方法 :稍加修改批量更新的方法。用时0.9s
UPDATE
mytable
SET
myfield1 =
CASE
id
WHEN
1
THEN
‘myvalue11‘
WHEN
2
THEN
‘myvalue12‘
WHEN
3
THEN
‘myvalue13‘
END
,
myfield2 =
CASE
id
WHEN
1
THEN
‘myvalue21‘
WHEN
2
THEN
‘myvalue22‘
WHEN
3
THEN
‘myvalue23‘
END
WHERE
id
IN
(1,2,3)
$classpath = array();
$bname = array();
$intro = array();
$classpagekey = array();
foreach ($arr as $key => $value) {
$classpath[] = $value[0];
$bname[] = $value[1];
$intro[] = $value[3];
$classpagekey[] = $value[2];
}
$classpaths = implode("‘,‘", array_values($classpath));
$classpaths = "‘".$classpaths."‘";
$sql = "UPDATE {$dbtbpre}enewsclass\n SET bname = CASE classpath \n";
foreach ($bname as $k=>$v) {
$sql .= sprintf("WHEN ‘%s‘ THEN ‘%s‘ \n", $classpath[$k], $v);
}
$sql .= " END,\n intro = CASE classpath \n";
foreach ($intro as $key1 => $value1) {
$sql .=sprintf("WHEN ‘%s‘ THEN ‘%s‘ \n",$classpath[$key1],$value1);
}
$sql .= " END,\n classpagekey = CASE classpath \n";
foreach ($classpagekey as $key2 => $value2) {
$sql .=sprintf("WHEN ‘%s‘ THEN ‘%s‘ \n",$classpath[$key2],$value2);
}
$sql .= " END\n WHERE classpath IN ($classpaths)";
$result = $empire->query("$sql");
if($result){
echo "success";
}else{
echo "error";
}
如有不懂可以私聊我。qq 517190435
原文地址:https://www.cnblogs.com/songadmin/p/10871022.html