我正在建立一个调查平台,我需要获得调查的平均答案率。 我目前正在做的是检索所有问题,然后将查看时间和回答时间分开。通过计算DB上的平均值而不是循环数千个结果,是否有更高效/更少资源消耗的方法?
这是我现在的工作代码,需要永远:
$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;
}
答案 0 :(得分:1)
当然可以进入Raw SQL:
而不是:
public void Add(int value)
{
if (root == null)
{
root = new Node(value);
return;
}
Node parent = null ,
res;
//finding the correct place
res = Find(value, root, ref parent);
if (res == null) //probably redunant
{
//once found create a node and asign it's parent
res = new Node(value);
res.m_parent = parent;
}
//EvaluateAVT(res);
}
private Node Find(int value, Node node, ref Node parent,bool justfind = false)
{
if (node.Data == value && justfind)
{
return node;
}
if (node.Data >= value)
{
if (node.m_left == null)
{
parent = node;
return node.m_left;
}
return Find(value,node.m_left,ref parent ,justfind);
}
else
{
if (node.m_right == null)
{
parent = node;
return node.m_right;
}
return Find(value, node.m_right, ref parent, justfind);
}
}
使用类似的东西:
$total_queries = Query::where('client_app_id','=', $app_id)->get();
答案 1 :(得分:1)
试
$total_showed = $total_queries->sum('showed')
$total_answered = $total_queries->sum('answered')
因为$ total_queries是一个集合,所以你可以使用它的sum方法 见https://laravel.com/docs/5.3/collections#method-sum 我认为这将是有效率的
答案 2 :(得分:0)
尝试这个聚合函数avg();像这样
$price = DB::table('orders')->where('finalized', 1)
->avg('price')