SQL内连接在三个表上

时间:2015-09-08 10:43:28

标签: sql inner-join

我有三张桌子需要检查才能找出教授活跃的课程。

  1. table_teacher
  2. table_course;和
  3. table_teacher_holds_course
  4. table_teacher看起来像这样:

    username | title
    ---------+----------
    john     | professor
    mark     | assistant
    

    table_course看起来像这样:

     course_code | course_name | semester | school_year
    -------------+-------------+----------+------------
     course_code1| course1     |semester1 | 2015
     course_code2| course2     |semester2 | 2015
     course_code3| course3     |semester3 | 2015
    

    table_teacher_holds_course看起来像这样:

    username | course_code
    ---------+-------------
     john    |course_code1
     mark    |course_code2
    

    当我在登录页面时拥有教授用户名时,我想在这三张桌子上做左内连接,以便从table_course中显示教授课程

    有人可以帮我这个,因为我第一次使用sql在几个表中加入搜索。

1 个答案:

答案 0 :(得分:1)

加入表格公共字段

SELECT * 
FROM table_teacher t
INNER JOIN table_teacher_holds_course hc ON t.username = hc.username
INNER JOIN table_course c ON hc.course_code = c.course_code

相关示例:

SELECT t.title, t.username, c.course_code, c.course_name, c.semester, c.school_year 
FROM table_teacher t
INNER JOIN table_teacher_holds_course hc ON t.username = hc.username
INNER JOIN table_course c ON hc.course_code = c.course_code
WHERE t.username = 'John'

结果:

title      username course_code  course_name semester  school_year 
professor  John     course_code1 course1     semester1 2015