首页 > 解决方案 > Laravel 嵌套查询

问题描述

我很难在 laravel 中获得正确的查询。

我有表考试。

id | exam_name 
---|------------
1  | First Exam
2  | Second Exam
3  | Third Exam

和学生成绩表

id  | exam_id | score
----|---------|-------
1   | 1       | 15
2   | 1       | 12
3   | 1       | 10
4   | 2       | 7
5   | 2       | 16
6   | 2       | 13

我想得到看起来像的所有考试的平均分数

exam_name   | average_score
------------|--------------
First Exam  | 12.33
Second Exam | 12
Third Exam  | 0 or NULL

我尝试过左连接,但每次考试返回多行。我也可以考虑使用嵌套查询,但不知道它在 Laravel 中是如何工作的。

标签: sqllaravel

解决方案


DB::table('exams')
   ->leftJoin('student_score','exam_id','=','exams.id')
   ->select('exam_name', DB::raw('AVG(score) as average_score'))
   ->groupBy('exam_name')->get();

您可以使用上述查询获得 AVG 分数。

希望这可以帮助。


推荐阅读