添加默认值的有效方法,其中值不是连接查询

时间:2017-04-28 18:59:50

标签: mysql

我有两张桌子:

teachers

|id|name|
| 1|jhon|
| 2|jane|
| 3| bob| 

classes

|id|student_id|hours|teacher_id|
| 1|         1|    1|         1|
| 2|         2|    2|         1|
| 3|         1|    2|         2|
| 4|         1|    2|         2|

我想生成一个查询,返回总小时数和每位老师参加的学生总数

|teacher_id|total_students|total_hours|
|         1|             2|          3|
|         2|             1|          4|
|         3|             0|          0|

我尝试了这两个表的连接,但是它没有返回没有课程的老师,所以我建立了一个联盟:

SELECT teachers.id  AS teacher_id, 
   Sum(classes.hours) AS total_hours, 
   Count(DISTINCT( classes.student_id )) AS total_students 
FROM teachers
   LEFT JOIN classes 
       ON teachers.id = classes.teacher_id 
UNION
SELECT teachers.id, 
   0, 
   0 
FROM teachers 
WHERE  teachers.id NOT IN(SELECT classes.teacher_id FROM classes)

有没有更有效的方法来处理这个问题?

2 个答案:

答案 0 :(得分:1)

select teachers.id, coalesce(t.cnt, 0), coalesce(t.hours, 0)  from teachers
left join 
(select sum(hours) as hours, count(distinct student_id) cnt, teacher_id  from classes group by teacher_id) t
on teachers.id = t.teacher_id

答案 1 :(得分:0)

试试这个:

SELECT 
    a.`id` AS `teacher_id`
    a.`name` AS `teacher_name`,
    COUNT(b.`hours`) AS `total_students`,
    SUM(IFNULL(b.`hours`,0)) AS `total_hours`
FROM `teachers` a
LEFT JOIN `classes` b
ON b.`teacher_id` = a.`id`
GROUP BY a.`id`
ORDER BY a.`id`