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

标签 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)

最佳答案

我认为这应该可行:

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

关于mysql - 查找具有相同的条目及其详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22730116/

相关文章:

mysql - Loopback4 MySQL自增ID

php - 使用PHPExcel制作自动生成的excel文件

mysql - 如何在 mysql 表中查找缺失的行(日期)?

sql - ORA-12728 : invalid range in regular expression

SQL Server 批量插入 - 0 行受影响

php - symfony2 mysql 基于时间间隔的排名

php - SQL 和 PHP 按发布的年、日和月对数据进行分组

mysql - 使用选择结果替换字符串

mysql - 文件大小:CSV 与 MySQL

sql - last_value() 和分组依据