如果数据为空,如何在查询中使用count计数0

时间:2018-08-20 06:55:38

标签: php mysql laravel

如何在查询中使用计数,如果数据为空则计数为0

我有3个表的用户,父级,签入日志

 user table
    id | name    | type
    1  | aion    | student
    2  | marry   | teacher
    3  | terst   | student

parent table
id | user_id | teacher_id
1  |   1     |  2
2  |   3     |  2

checkin_log table
id | user_id | type_attendence
1  |  1      |  late
2  |  3      |  absence


 DB::table("parent AS p")
->leftJoin('users AS u', 'p.user_id', '=', 'u.id')
->leftJoin('checkin_log AS c', 'p.user_id', '=', 'c.user_id')
->select('u.id','u.name', DB::raw('COUNT(c.type_attendance) as total'))
->where('p.teacher_id',2)
->where(function ($q) {
                        $q->where('c.type_attendance', 'absence')
                    })
->groupBy('u.id')
->get()->toArray();

此查询仅打印具有type_attendance的数据,它将显示

id | name | total
3  | terst|   1

如何计算'c.type_attendance' = 'absence'是否为空,total = 0我想显示为:

id | name | total
1  | aion |   0
3  | terst|   1

注意:我需要使用where('c.type_attendance', 'absence'),因为我想计算每个学生的缺勤

2 个答案:

答案 0 :(得分:2)

您可以简单地使用mysql的IFNULL

DB::table("parent AS p")
->leftJoin('users AS u', 'p.user_id', '=', 'u.id')
->leftJoin('checkin_log AS c', 'p.user_id', '=', 'c.user_id')
->select('u.id','u.name', DB::raw('IFNULL(COUNT(c.type_attendance),0) as total'))
->where('p.teacher_id',2)
->where(function ($q) {
                        $q->where('c.type_attendance', 'absence')
                    })
->groupBy('u.id')
->get()->toArray();

答案 1 :(得分:0)

此方法也有效

DB::table("parent AS p")
->leftJoin('users AS u', 'p.user_id', '=', 'u.id')
->leftJoin('checkin_log AS c', function($join)
                    {
                        $join->on('p.user_id', '=', 'c.user_id')
                        ->where('c.type_attendance','abcense');
                    })
->select('u.id','u.name', DB::raw('COUNT(c.type_attendance) as total'))
->where('p.teacher_id',2)
->groupBy('u.id')
->get()->toArray();