You should see the query that is executed and then inspect it to see what the bottlenecks are with the EXPLAIN prefix to the query.
Jul 16, 2021
5
Level 1
Count Query in Laravel taking to long to respond. How to Optimize it ?
Hi, In my database i have like 10-20 companies only but having 7,000 - 8,000 rows in other tables like table1,2,3,4. When i run my query of count it just take too long to respond and my page doesn't even load. Its gives me error
Maximum execution time of 60 seconds exceeded
How can i optimized my query to run faster and dont give me error ?
$company = Companies::select('companies.*','table4.name as type',
DB::raw('COUNT(DISTINCT users.id) as total_users'),
DB::raw('COUNT(DISTINCT table2.id) as total_val1'),
DB::raw('COUNT(DISTINCT table5.id) as total_val2'),
DB::raw('COUNT(DISTINCT table3.id) as total_val3'))
->leftJoin('table4','table4.id','companies.type_id')
->leftJoin('users','users.company_id','companies.id')
->leftJoin('table2','table2.company_id','companies.id')
->leftJoin('table5','table5.company_id','companies.id')
->leftJoin('table3','table3.company_id','companies.id')
->groupBy('companies.id')
->paginate($perPage);
Please or to participate in this conversation.