查找具有相同条目的条目及其详细信息

时间:2014-03-29 10:53:39

标签: mysql sql

我需要帮助来查询一个查询,该查询会拉出一个具有相同条目的条目。教师可以选择任何科目进行教学,学生可以选择任何科目进行教学。需要找一位选择教授同一学科组合的教师。

表学生

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)

1 个答案:

答案 0 :(得分: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