繁体   English   中英

我们如何在 laravel 的 select() 中使用 count() 和条件 sql?

[英]How can we use count() with conditional sql in select() of laravel?

我有两个表,如下所示。 我正在使用 Laravel DB 方法加入此表。 但是我不知道如何根据失败或通过来计算学生的分数。 0-failed 1-passed

预期结果:

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

students

`+----+-----------+
 | id |   name    |
 +----+-----------+
 |  1 | John Doe  |
 |  2 | Mark P    |
 |  3 | Pen Henry |
 +----+-----------+`

students_marks

 +----+------------+-------+-----------+
 | 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')
        ->join('contacts', 'students.id', '=', 'students_marks.user_id')
        ->select('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 到 select 中,假设student#id是该表的主键列,上述GROUP BY查询中的name字段是可以接受的。 如果上面的查询给出了ONLY_FULL_GROUP_BY错误,那么只需将s.name添加到GROUP BY子句。

 $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_mark sm', 's.id', '=', 'sm.student_id') ->groupBy('s.id','s.name') ->selectRaw("s.id,s.name,SUM(sm.is_failed) AS count_failed,SUM(sm.marks) as total_marks") ->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM