我正在搭建一个调查平台,我需要得到调查的平均应答率。我现在正在做的是检索所有的问题,然后划分观看时间和回答时间。是否有一种更有效/更少的资源消耗方法,通过计算数据库上的平均值,而不是通过数千个结果循环?
这是我现在的工作代码,需要永远:
$total_showed = 0;
$total_answered = 0;
$total_queries = Query::where('client_app_id','=', $app_id)->get();
foreach ($total_queries as $app_query) {
$total_showed = $total_showed + $app_query->showed;
$total_answered = $total_answered + $app_query->answered;
}
if ($total_showed > 0) {
$total_arate = round(($total_answered / $total_showed) * 100, 1);
} else {
$total_arate = 0;
}
尝试$total_showed = $total_queries->sum('showed')
$total_answered = $total_queries->sum('answered')
因为$total_queries是一个集合,你可以使用它的sum方法看到https://laravel.com/docs/5.3/collections method-sum我觉得这样更有效率
当然你可以进入Raw SQL:
代替:
$total_queries = Query::where('client_app_id','=', $app_id)->get();
可以这样写:
$total_queries = Query::select(DB::raw('SUM(showed) as counter, SUM(answered) as answered'))
->where('client_app_id','=', $app_id)->get();
尝试这个聚合函数avg();像这样
$price = DB::table('orders')->where('finalized', 1)
->avg('price')