过滤条件的连接

时间:2013-02-07 04:08:22

标签: sql postgresql

我有3个表,名为

students (id, name)
subjects (id, name, is_published)
student_subjects (id, student_id, subject_id)

学生参加的科目是student_subjects。但有些情况下student_subjects包含NULL subject_id学生

以下是Students

的数据
1;"John"
2;"Ahmeah"
3;"Dina"
4;"Leo"
5;"Lenon"

主题表

1;"Computer Sci";1
2;"Physics";1
3;"Bio";1
4;"Maths";0

Student_subjects

1;1;1
2;1;2
3;1;4
4;2;1
5;2;3
6;2;4
7;3;2
8;4;1
9;5;NULL

目前,为了取得所有学生的科目,并显示没有附加科目的学生的姓名,我使用的查询如下

SELECT
  students.*,
  inners.name
FROM
  students
  LEFT JOIN ( SELECT
                student_id,
                subjects.name
              FROM
              student_subjects
              JOIN subjects ON ( student_subjects.subject_id = subjects.id AND subjects.is_published = 1)
              ) AS inners ON (inners.student_id = students.id )

是否有更好的方法来执行相同的http://sqlfiddle.com/#!12/9cf93/12

1 个答案:

答案 0 :(得分:1)

SELECT s.*, su.name AS SubjName
FROM students AS s
LEFT JOIN student_subjects AS ss ON ss.student_id = s.id
LEFT JOIN subjects AS su ON su.id = ss.subject_id

与您列出的那个相同。这就是你追求的目标吗?