Php 在laravel的select()中,如何将count()与条件sql结合使用?
我有两张表,如下所示。我正在使用Laravel DB方法加入这个表。但我不知道我如何才能得到学生的分数计数作为失败或通过<代码>0-失败Php 在laravel的select()中,如何将count()与条件sql结合使用?,php,laravel,join,count,Php,Laravel,Join,Count,我有两张表,如下所示。我正在使用Laravel DB方法加入这个表。但我不知道我如何才能得到学生的分数计数作为失败或通过0-失败1-通过 预期结果: 1. Student Name 2. Student Id, 3. Count of failed based on student Id as count_failed 4. Total Marks based on student Id as total_marks 表学生 `+----+-----------+ | id | name
1-通过
预期结果:
1. Student Name
2. Student Id,
3. Count of failed based on student Id as count_failed
4. Total Marks based on student Id as total_marks
表学生
`+----+-----------+
| id | name |
+----+-----------+
| 1 | John Doe |
| 2 | Mark P |
| 3 | Pen Henry |
+----+-----------+`
表学生分数:
+----+------------+-------+-----------+
| id | student_id | marks |is_failed |
+----+------------+-------+-----------+
| 1 | 1 | 55 | 0 |
| 2 | 2 | 44 | 1 |
| 3 | 1 | 11 | 1 |
| 4 | 2 | 10 | 0 |
| 5 | 2 | 11 | 1 |
| 6 | 2 | 20 | 0 |
+----+------------+-------+-----------+
下面是我使用的查询:
$users=DB::table('users'))
->加入('contacts'、'students.id'、'='、'students\u marks.user\u id'))
->选择('student.*')
->get();
我无法了解如何在laravel的select()
中将count()
与条件SQL一起使用?使用条件聚合:
$users = DB::table('students s')
->leftJoin('students_mark sm', 's.id', '=', 'sm.user_id')
->groupBy('sm.id')
->select(DB::raw('s.id, s.name, SUM(sm.is_failed) AS num_failed, COUNT(sm.user_id) AS total_cnt'))
->get();
这对应于以下原始MySQL查询:
SELECT
s.id,
s.name,
SUM(sm.is_failed) AS num_failed,
COUNT(sm.user_id) AS total_cnt
FROM students s
LEFT JOIN students_marks sm
ON s.id = sm.user_id
GROUP BY
s.id;
注意:在ANSI SQL中,可以在上述分组依据
查询中选择名称
字段,假设学生#id
是该表的主键列。如果上面的查询给出了一个ONLY\u FULL\u GROUP\u BY
错误,那么只需将s.name
添加到groupby
子句中即可
$users = DB::table('users')
->join('contacts', 'students.id', '=', 'students_marks.user_id')
->select('student.*', DB::raw("count(students_marks.is_failed) as count")))
->where('status', '=', 0)
->get();
试试这个。
如果不清楚或不起作用,请参考此代码段
$table = DB::table('students_marks');
$table = $table->select(
\DB::raw('SUM(if(is_failed = '0', 1, 0)) AS failed'),
\DB::raw('SUM(if(is_failed = '1', 1, 0)) AS passed'),
\DB::raw('SUM(marks) AS total'));
$table = $table->Join('students', 'students.id', '=', 'students_marks.student_id');
$table = $table->get();
试试这个
$users=DB::table('students's'))
->leftJoin('students\u mark sm'、's.id'、'='、'sm.student\u id')
->groupBy('s.id','s.name')
->选择原始(“s.id,s.name,总和(sm.is\U失败)作为计数\U失败,总和(sm.marks)作为总\U分数”)
->get()代码>那么你想计算及格和不及格分数吗?我有20多个字段,我需要将这20多个字段添加到groupBy()中
否则给我的错误是仅由
@Tim biegeleisensen进行分组,因此我们无法获得失败计数@Tim biegeleisensen只需确保添加到SELECT
子句的id
之外的每个附加字段也出现在GROUP BY
子句中。无论如何,我已经回答了你原来的问题。我认为我们缺少了“SUM(sm.is_failed)AS num_failed”的计数逻辑,但是我们需要countNo,你不需要,因为当发生故障时,is_failed
为1,否则为零,所以取每个学生的此字段的总和即为故障数。