1

I have below tow table table 1: The teacher table

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

以下のように、生徒テーブルに表示される人の数が含まれている教師から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

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 に答える