PHP-Laravel-直接从Elount获得平均值,而不必循环查看结果
我正在建立一个调查平台,我需要得到调查的平均回答率。 我目前正在做的是检索所有问题,然后划分查看次数和回答次数。是否有一种更高效/更少资源消耗的方法,通过计算数据库的平均值而不循环数千个结果 这是我现在的工作代码,它将永远持续下去:PHP-Laravel-直接从Elount获得平均值,而不必循环查看结果,php,mysql,laravel,eloquent,laravel-5.2,Php,Mysql,Laravel,Eloquent,Laravel 5.2,我正在建立一个调查平台,我需要得到调查的平均回答率。 我目前正在做的是检索所有问题,然后划分查看次数和回答次数。是否有一种更高效/更少资源消耗的方法,通过计算数据库的平均值而不循环数千个结果 这是我现在的工作代码,它将永远持续下去: $total_showed = 0; $total_answered = 0; $total_queries = Query::where('client_app_id','=', $app_id)->get(); fore
$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;
}
当然可以进入原始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();
当然可以进入原始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();
试一试
$total\u show=$total\u querys->sum('show')
$total\u answered=$total\u querys->sum('answered')
由于$total_查询是一个集合,因此可以使用它的sum方法
看见
这将是一个高效的方法,我想试试看
$total\u show=$total\u querys->sum('show')
$total\u answered=$total\u querys->sum('answered')
由于$total_查询是一个集合,因此可以使用它的sum方法
看见
这将是一个高效的方法,我想试试这个聚合函数avg();像这样
$price = DB::table('orders')->where('finalized', 1)
->avg('price')
尝试此聚合函数avg();像这样
$price = DB::table('orders')->where('finalized', 1)
->avg('price')
如果你不去拿,而是去数,你会把数拿回来的。:)如果你不去拿,而是去数,你会把数拿回来的。:)
sum
方法是再次查询数据库还是由PHP处理?不是,它在集合类中。。。检查该类的文档sum
方法是否再次查询数据库,还是由PHP处理?不,不在集合类中。。。检查该类的文档