复杂的连接查询

时间:2012-03-18 19:03:59

标签: sql join

我最初是通过四个单独的查询来完成此操作的 - 我认为是时候通过使用连接优化我的代码...

我有四张桌子(如下图所示):

[sl_student_course]
student_id (int 11)
------------------
course_id (int 11)
------------------

[sl_project_course]
project_id(int 11)
------------------
course_id (int 11)
------------------

[sl_project]
project_id (int 11) - Primary Key -
_____________________
professor_id (int 11)
---------------------
project_name (varchar 50)

[sl_professor]
professor_id(int 11) - Primary Key -
_____________________
professor_name (varchar 50)
---------------------
project_email (varchar 50)


我需要哪些信息?

我需要来自sl_projectsl_professor sl_student_course.course_id = sl_project_course.course_id的所有数据,然后我需要使用project_id中的sl_project_course < / p>

SO ...

sl_student_course.course_id - &gt; sl_project_course.project_id - &gt; sl_project.professor_idsl_project.project_name, - &gt; sl_professor.professor_namesl_professor.professor_name

这有意义吗?

  • 如果它没有,这是另一个例子!
sl_student_course
course_id |  1

sl_project_course
project_id | 1
course_id  | 1

sl_project
project_id | 1
professor_id | 2
project_name | project1

sl_professor
professor_id | 2
professor_name | John Doe
professor_email | John@Doe.com

2 个答案:

答案 0 :(得分:4)

希望我理解你的表关系,教授加入了项目(在sl_project表中)。

这将为您提供项目和教授数据(使用TSQL):

SELECT P.project_name, F.professor_name, F.professor_email
FROM sl_project P
    INNER JOIN sl_professor F ON F.professor_id = P.professor_id

    -- Not sure where course is coming into play, since you aren't selecting
    -- anything from the students/course table, but if you need to ensure there is a
    -- course for this project and students in the course, these joins are necessary.
    INNER JOIN sl_project_course C ON C.project_id = P.project_id
    INNER JOIN sl_student_course S ON S.course_id = C.course_id
WHERE P.project_id = @project_id

答案 1 :(得分:1)

尝试以下几点:

 select sl_project.project_name, sl_professor.professor_name, sl_professor.professor_email 
 from sl_student_course
 natural join sl_project_course
 natural join sl_project
 natural join sl_professor

自然连接很好,因为它更喜欢约定优于配置 - 所以如果你以预期的方式进行数据库设计,那么你就可以安全地工作。

更新:根据请求的特定字段替换*。