2014-04-01 50 views
3

我在我的MySQL數據庫中有一個大表。我想查看其中的一列,並將其傳遞給一個函數,以查看它是否存在於另一個表中,如果不在此處創建它。在檢索MySQL表時克服PHP內存耗盡或執行時間錯誤

但是,我總是面對內存耗盡或執行時間錯誤。

//Get my table 
$records = DB::($table)->get(); 

//Check to see if it's fit my condition 
foreach($records as $record){ 
    Check_for_criteria($record['columnB']); 
} 

然而,當我這樣做,我得到一個內存耗盡錯誤。

所以我有試過聲明

//Get min and max id 
$min = \DB::table($table)->min('id'); 
$max = \DB::table($table)->max('id'); 

//for loop to avoid memory problem 
for($i = $min; $i<=$max; $i++){ 
    $record = \DB::table($table)->where('id',$i)->first(); 

    //To convert in array for the purpose of the check_for_criteria function 
    $record= get_object_vars($record); 
    Check_for_criteria($record['columnB']); 
} 

但會這樣,我得到了一個最大執行時間錯誤。

FYI的check_for_criteria功能是一樣的東西

check_for_criteria($record){ 
    $user = User::where('record', $record)->first(); 
    if(is_null($user)){ 
     $nuser = new User; 
     $nuser->number = $record; 
     $nuser->save(); 
    } 
} 

我知道我可以ini_set('memory_limit', -1);但我寧願找到一個方法來限制在某些方面我的內存使用情況,或至少它散佈某種方式。

我應該在流量較低時在後臺運行這些操作嗎?任何其他建議?

+0

懷疑你的MySQL查詢沒有得到很好的優化。直接執行查詢需要多長時間才能執行。它返回多少數據?索引好嗎? – AllInOne

+0

'SELECT * FROM Table'需要0.0006秒 – Wistar

+1

不錯!你真的需要*嗎?它返回多少數據?也許PHP解析它有困難? – AllInOne

回答

2

我通過將請求限制在ColumnB中的不同值來解決了我的問題。

//Get my table 
$records = DB::($table)->distinct()->select('ColumnB')->get(); 

//Check to see if it's fit my condition 
foreach($records as $record){ 
    Check_for_criteria($record['columnB']); 
}