Laravel查找平均结果在其他表中

时间:2019-11-24 17:24:25

标签: mysql sql laravel laravel-query-builder

我在Laravel中得到了这个查询:

stack App/Main.hs

结果:

DB::table('score')
    ->select('score.score_nl', DB::raw('count(*) as total'), DB::raw('round(avg(rating_results.rating)) as final_rating'))
    ->join('rating', 'rating.score_id', '=', 'score.id')
    ->join('rating_results', 'rating.rating_result_id', '=', 'rating_results.id')
    ->groupBy('score_nl')
    ->get();

我要在此表中创建一个名为[{"score_nl":"emphatisch","total":1,"final_rating":"1"},{"score_nl":"huilen","total":2,"final_rating":"3"},{"score_nl":"knuffelig","total":1,"final_rating":"1"},{"score_nl":"zindelijkheid","total":2,"final_rating":"3"}] 的表(请参见图片) 查找rating_results并获取关联的final_rating

enter image description here

我如何在laravel中做到这一点?

有任何问题请告诉我!

-编辑-

我已经尝试过了

result_en

但随后出现此错误:

$q = Result::select('result_nl')
    ->whereColumn('rating_results.rating', 'final_rating')
    ->whereColumn('rating_results.score_id', 'score_id')
    ->getQuery();

DB::table('score')
    ->select('score.score_nl', DB::raw('count(*) as total'), DB::raw('round(avg(rating_results.rating)) as final_rating'))
    ->join('rating', 'rating.score_id', '=', 'score.id')
    ->join('rating_results', 'rating.rating_result_id', '=', 'rating_results.id')
    ->selectSub($q, 'result_nl')
    ->groupBy('score_nl')
    ->get();

似乎我需要使用joinSub

1 个答案:

答案 0 :(得分:7)

你很近。您可以在此处使用joinSub

据您的尝试,您还需要加入score_id吗?如果是这样,这是解决方案:

// Your initial query
$query = DB::table('score')
    ->selectRaw('
        score.score_id, 
        score.score_nl, 
        count(*) as total, 
        round(avg(rating_results.rating)) as final_rating
    ')
    ->join('rating', 'rating.score_id', '=', 'score.id')
    ->join('rating_results', 'rating.rating_result_id', '=', 'rating_results.id')
    ->groupBy('score_nl');

// Now use joinSub (just like simple joins above)
$result = DB::table('rating_results')
    ->joinSub($query, 'subtable', function($join) {
        $join->on('subtable.final_rating', '=', 'rating_results.rating')
             ->on('subtable.score_id', '=', 'rating_results.score_id');
    })
    ->selectRaw('subtable.*, rating_results.result_en')
    ->get();

但是我个人会在这里使用原始SQL。当查询变得太麻烦时,最好避免使用ORM,这样您就不仅限于其功能了:

$result = DB::select('
    select subtable.*, rating_results.result_en
    from rating_results
    join (
        select
            score.score_nl, 
            count(*) as total, 
            round(avg(rating_results.rating)) as final_rating 
        from score
        join rating on rating.score_id = score.id
        join rating_results on rating.rating_result_id = rating_results.id 
        group by score_nl
    ) as subtable on subtable.final_rating = rating_results.rating
');