连接3个表的SQL查询

时间:2015-04-04 12:57:55

标签: sql join

我刚开始尝试使用表关系并加入查询。

我有3个表:peoplecoursebridge

我想做的是,能够选择一个student,并获得他所参加的所有course_names,如果他是学生:像

SELECT(.......) where student_name = 'what I want'.

我不打算在这里发布代码,因为我尝试的一切都很乱。

people

people_id   student_name    
1            Alice
2            Bob
3            Caroline
4            David
5            Emma

course

course_id   course_name
1           IT
2           art
3           sports
4           math
5           whatever

bridge

people_id course_id people_role
1          1        student
1          3        student
1          5        student
2          1        student
2          2        student
2          5        student
4          1        teacher

1 个答案:

答案 0 :(得分:0)

SELECT student_name, course_name
FROM people p
  INNER JOIN bridge b
    ON p.people_id = b.people_id
  INNER JOIN course c
    ON b.course_id = c.course_id
  WHERE p.student_name = 'Alice' AND b.people_role = 'student';

以下是其运行示例:http://sqlfiddle.com/#!9/cd5f1/2

或者您希望结果看起来像student_name | course1,course2,...

SELECT student_name, group_concat(course_name)
FROM people p
  INNER JOIN bridge b
    ON p.people_id = b.people_id
  INNER JOIN course c
    ON b.course_id = c.course_id
  WHERE p.student_name = 'Alice' AND b.people_role = 'student'
  GROUP BY student_name

http://sqlfiddle.com/#!9/cd5f1/3