0

我有 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

4

1 回答 1

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

做和你列出的一样的事情。这就是你所追求的吗?

于 2013-02-07T04:16:38.587 回答