使用连接优化查询

时间:2013-01-11 00:14:07

标签: mysql sql join refactoring

如何使用连接完成查询。我是数据库新手。这个查询工作正常.. 但我想让它更加坚固

   $query = "SELECT student_id 
FROM students
WHERE student_id
IN (
    SELECT student_id
    FROM class_students
    WHERE class_id
        IN (
            SELECT class_id
            FROM class_course
            WHERE teacher_id =". $_SESSION['teacher_id']."))";

还有其他方法吗

3 个答案:

答案 0 :(得分:5)

使用IN可以转换为正确的连接:

SELECT s.student_id 
FROM students s
JOIN class_students cs ON cs.student_id = s.student_id
JOIN class_course c ON c.class_id = cs.class_id
WHERE teacher_id = ?

请注意,我删除了(不相关的)应用程序语言细节(perl?),只留下回答问题的SQL。

答案 1 :(得分:1)

$query = "select students.student_id
from class_course left outer join class_students on 
        class_course.class_id = class_students.class_id
    left outer join students on 
        class_students.student_id = students.student_id
where class_course.teacher_id = ". $_SESSION['teacher_id']

答案 2 :(得分:1)

  $query = "SELECT s.student_id 
FROM students s
    INNER JOIN class_students cs
        ON s.student_id = cs.student_id
    INNER JOIN class_course cc
        ON cs.class_id = cc.class_id
            AND cc.teacher_id =". $_SESSION['teacher_id']."))