mysql 如何优化laravel查询,以便从另一个联接表中查找平均值

vxf3dgd4  于 2022-12-03  发布在  Mysql
关注(0)|答案(1)|浏览(107)

我的查询(DB::raw(AVG('pt.progress')))这部分目前正在抛出错误

$query = DB::table('projects as p')
    ->leftJoin('projects_tasks as pt','pt.project_id', 'p.id')
    ->select(
        'p.id', 'p.project_name', DB::raw(AVG('pt.progress')) //this is where I need the average
    );
$query->orderBy($order, $dir);
if ($limit != -1) {
    $query->skip($start)->take($limit);
}
$records = $query->get();

表格结构:

projects:
========
id
project_name
...
...

projects_tasks:
===============
id
project_id,
parent, //0 or 1 
progress //exmaple value 0.00 to 1.00

如何获得平均进度,其中parent_id = 0且project_id相同?
如果我创建一个函数并在循环中传递它,下面的查询确实可以工作,但是,我想优化它,并通过连接上面的查询来运行它。

$data_row = DB::table('projects_tasks')
     ->select(DB::raw('(SUM(progress)*100)/count(progress) as project_progress'))
     ->where(['project_id' => $project_id, 'parent' => 0])
     ->get();
nfzehxib

nfzehxib1#

您的查询似乎有语法错误,问题出在这里DB::raw(AVG('pt.progress'))
因为您使用的是原始查询,所以参数应该是一个字符串,所以必须用引号/双引号将其括起来。

$query = DB::table('projects as p')
    ->leftJoin('projects_tasks as pt','pt.project_id', 'p.id')
    ->select(
        'p.id', 'p.project_name', DB::raw("AVG('pt.progress')")
    );
$query->orderBy($order, $dir);
if ($limit != -1) {
    $query->skip($start)->take($limit);
}
$records = $query->get();

相关问题