我想優化我的查詢,我正在使用Laravel執行。我爲我的項目使用MySQL,並且我有一個名爲locations
的表。它有超過200萬條記錄。 當我執行下面的代碼時,它太慢了。如何優化我的查詢以提高速度?laravel緩慢查詢問題
foreach ($employees as $employee){
$percentage = 0;
if ($employee->position->zones->count() > 0) {
if($employee->position->zones->first()->workingzones->count() > 0) {
$workingZone = $employee->position->zones->first()->workingzones->last();
$tagCode = $employee->rfids->first()->rfid_id;
$zoneTime = DB::table('location')
->select(DB::raw('count(*) as count'))
->where('tagCode', $tagCode)
->where('xLocation', '>', $workingZone->x1)
->where('xLocation', '<', $workingZone->x3)
->where('yLocation', '>', $workingZone->y3)
->where('yLocation', '<', $workingZone->y1)
->where('locationDate', '>=',''.$currentDate.' 00:00:01')
->where('locationDate', '<=', $currentDate. ' 23:59:59')
->get();
$totalWorkedTime = DB::table('location')
->select(DB::raw('count(*) as count'))
->where('tagCode', $tagCode)
->where('locationDate', '>=',''.$currentDate.' 00:00:01')
->where('locationDate', '<=', $currentDate. ' 23:59:59')->get();
if ($zoneTime->first()->count == 0 || $totalWorkedTime->first()->count == 0) {
$percentage = 0;
}else {
$percentage = (int)ceil(($zoneTime->first()->count /12)* 100/($totalWorkedTime->first()->count/12));
}
}
}
$employee->percentage = $percentage;
}
使用大塊用於獲取結果 –
還是一樣什麼都沒有改變 –