1

我有下面的拖表表1:教师表

teacher_id   teacher_name
1            xx
2            yy
3            zz

表 2:学生表

stu_id       stu_name     tearcher1_id     teacher2_id    tearcher3_id
1            aa           1                2 
2            bb           2                3
3            cc           1

我想从老师那里得到一个 sql 语句的列表,包括出现在学生表中的人数,如下所示:

teacher_id      teacher_name          num_selected_by_stu
1               xx                    2
2               yy                    2
3               zz                    1

我在sql下面试过但似乎不起作用,

    select * from teatcher t1 
    left join (
    select stu_id,tearcher1_id,tearcher2_id,tearcher3_id,count(stu_id) as num_selected_by_stu from student 
    group by stu_id,tearcher1_id,tearcher2_id,tearcher3_id) t2 
    ON ( t2.teacher1_id=t1.teacher_id or t2.teacher2_id=t1.teacher_id or t2.teacher3_id=t1.teacher_id)

而且,有人可以帮忙吗?

4

3 回答 3

1
SELECT 
  teacher_id
  teacher_name
  NVL(num1, 0) + NVL(num2, 0) + NVL(num3,0) as num_selected_by_stu
FROM 
  teacher t
  left outer join ( SELECT count(*) as num1, tearcher1_id FROM student group by tearcher1_id ) t1 on t1.tearcher1_id = t.tearcher_id
  left outer join ( SELECT count(*) as num2, tearcher2_id FROM student group by tearcher2_id ) t2 on t2.tearcher2_id = t.tearcher_id
  left outer join ( SELECT count(*) as num3, tearcher3_id FROM student group by tearcher3_id ) t3 on t3.tearcher3_id = t.tearcher_id
;
于 2013-07-09T08:18:00.853 回答
0

请试试:

SELECT 
    *,
    (SELECT 
        COUNT(*) 
    FROM 
        Student t2 
    WHERE 
        t1.teacher_id=t2.tearcher1_id OR 
        t1.teacher_id=t2.teacher2_id OR 
        t1.teacher_id=t2.tearcher3_id) num_selected_by_stu
FROM 
    Teacher t1
于 2013-07-09T07:18:35.300 回答
0
select t.teacher_id,t.teacher_name from teacher t ,

inner join student s
 on t.teacher_id = s.teacher_id
 where 
 case when teacher1_id < 35  then 0 else 1 end +
 case when teacher1_id < 35  then 0 else 1 end +
 case when teacher1_id < 35  then 0 else 1 end +
 end 
 as [num_selected_by_stu]
于 2013-07-09T07:37:27.740 回答