我對有一個8萬條數據的表進行了一次去重操作,其中有將近6萬條的重復數據需要被刪除。考慮到可能會產生對數據庫的高IO操作,我選擇進行刪除算法的優化。
public function getArray()
{
set_time_limit(120);
$DB = M('code');
$handle = @fopen("C:/Users/Administrator/Desktop/xcu/UserData/user.sql", "r");
$t1 = microtime(true);
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
if (preg_match('/[\d]{10}\b/', $buffer, $match)) {
$array['sid'] = $match[0];
if (preg_match('/[\x7f-\xff]+/', $buffer, $match)) {
$array['name'] = iconv('gbk', 'utf-8', $match[0]);
if (preg_match('/\d{17}[\d|X|x]/', $buffer, $match)) {
$array['idcode'] = $match[0];
}
}
}
if (!empty($array)) {
$DB->data($array)->add();
}
}
fclose($handle);
}
$t2 = microtime(true);
echo '耗時' . round($t2 - $t1, 3) . '秒';
}
public function delData()
{
set_time_limit(120);
$DB = M('code');
$res = $DB->field('min(id) as id')->group('idcode')->select();
$t1 = microtime(true);
$arr = "";
$count = 0;
foreach ($res as $val) {
$count++;
//var_dump($val['id'].'<br>');
$arr.= ",".$val['id'];
if ($count % 1000 == 0){
echo substr($arr,1).'<br>';
$map["id"] = array('in', substr($arr,1));
$sqlres = $DB->where($map)->delete();
if ($sqlres){
echo "批次刪除成功!";
}
$arr = "";
}
}
$t2 = microtime(true);
echo '耗時' . round($t2 - $t1, 3) . '秒';
}
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。