[英]SQL Laravel 5.7 unique() on collection really slow
我正在嘗試根據具有索引的mobile
列通過 Laravel collect
和unique
方法計算唯一記錄的數量。 我有 200,000 行,並且有一個名為optout_csv_schedule_id
的列,它與移動設備一起有一個索引。 現在,執行查詢已經運行了超過 15 分鍾,我該如何提高它的性能,因為我需要計算 200,000 中唯一數字的數量,我當前的查詢是:
/**
* Get valid lead count
*/
protected function getValidLeadCount($schedule_id)
{
$optoutConnectionLogs = OptoutConnectionLog::where('optout_csv_schedule_id', $schedule_id)
->get();
// no leads
if (!$optoutConnectionLogs) {
return 0;
}
// count total unique leads
$uniqueLeads = collect($optoutConnectionLogs)->unique('mobile')->count();
return $uniqueLeads;
}
您沒有使用數據庫來執行唯一操作,您已經使用->get()
獲得了記錄,並且正在使用 PHP/Laravel 來執行此操作。 這將比使用數據庫慢得多。
使用distinct()
獲取唯一記錄,例如:
$optoutConnectionLogs = OptoutConnectionLog::where('optout_csv_schedule_id', $schedule_id)
->select('mobile')
->distinct()
->get();
似乎很難計算Laravel
中 200,000 個唯一數字的數量。 嘗試改變如下:
protected function getValidLeadCount($schedule_id)
{
$uniqueLeads = OptoutConnectionLog::where('optout_csv_schedule_id', $schedule_id)
->distinct('mobile')
->count('mobile');
return $uniqueLeads;
}
你把所有的數據讀入memory,轉換成PHP個對象,然后迭代統計數字。 您創建的數據庫索引根本沒有被使用。
您的需求應該簡化為以下代碼
return OptoutConnectionLog::where('optout_csv_schedule_id', $schedule_id)
->distinct('mobile')
->count();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.