sql - 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 中是如何工作的。
解决方案
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 分数。
希望这可以帮助。
推荐阅读
- apache-kafka - Kafka KTable Materialized-State-Store 控制
- calculation - DialogFlow CX 计算值
- powershell - PowerShell 导出
- r - 如何根据变量的首字母对新变量进行分组?
- android - Android:对多个商店使用相同的 applicationId 是一种好习惯吗?
- swiftui - 删除具有绑定布尔值的列表项 - SwiftUI
- arrays - 在递归函数中键入不匹配数组(VBA)
- odata - 针对真实服务器的“无法获取上下文”错误,适用于模拟服务器
- javascript - 反应秒表计时器计数 - 不重置秒
- openseadragon - openseadragon:无法 [Object object]:加载图像时出错