2014-03-29 58 views
1

我需要擰查詢這將拉動具有相同的有很多的項目提供幫助。教師可以選擇任何科目教學,學生可以選擇任何科目教授。需要找到一位選擇教學的老師,他們選擇了同一個學生選擇的科目組合。查找具有相同的有它的細節一起許多入門

表學生

id name 
1 x 
2 y 

表student_Subjects

id subject_id student_id 
1 1   1 
2 2   1 
3 1   2 

教師

id name 
1 tx 
2 ty 

表teacher_subjects

id subject_id teacher_id 
1 1   2 
2 2   2 
3 1   1 

主題

id name 
1 English 
2 Maths 

現在需要找到誰已經選擇教科目相同的學生x,其中教師和學生的名字沿老師。

我曾問這讓我的結果,而不學生名字和教師名字類似的問題。 這裏是該查詢:

SELECT GROUP_CONCAT(subject_id ORDER BY subject_id) as teacher_concat ,teacher_id 
     FROM teacher_subjects 
     GROUP BY teacher_id 
     HAVING teacher_concat IN 
        (SELECT group_concat(subject_id ORDER BY subject_id) 
        FROM student_subjects GROUP BY student_id) 

回答

0

我認爲這應該工作:

select 
     teacher.id, 
     teacher.name, 
     student.id, 
     student.name 
from 
     teacher, 
     student, 
     (select 
       teacher_id, 
       GROUP_CONCAT(
         distinct subject_id 
         order by subject_id 
         separator ' ' 
       ) x 
     from 
       teacher_subjects 
     group by 
       teacher_id 
     ) t, 
     (select 
       student_id 
       GROUP_CONCAT(
         distinct subject_id 
         order by subject_id 
         separator ' ' 
       ) x 
     from 
       student_subjects 
     group by 
       student_id 
     ) s 
where 
     t.x=s.x and 
     t.teacher_id=teacher.teacher_id and 
     s.student_id=student.student_id 
+0

給出了一個錯誤:你在你的SQL語法錯誤;檢查對應於你的MySQL服務器版本「從 teacher_sub通過subject_id )M 組」在行使用近13個@Lajos – nshastri

+0

得益於正確的語法手冊。我固定了兩件事,我希望它有幫助。 –

相關問題