Mysql- SELECT列'A'甚至为NULL

时间:2018-09-21 14:44:43

标签: mysqli

表A包含学生姓名,表B和C包含班级和学生的身影。 我想展示所有学生并参加他们的出席。问题是我无法显示所有未检查状态的学生。 我在哪里检查了学生的状况就可以了,但是,如果在给定的班级,在给定的日期和给定的科目中没有检查过的存在,则不会显示任何内容。

我的查询:

SELECT student.id_student, CONCAT(student.name,' ' ,student.surname) as 'name_surname',pres_student_present, pres_student_absent, pres_student_justified, pres_student_late, pres_student_rel, pres_student_course, pres_student_delegation, pres_student_note FROM student
    LEFT JOIN class ON student.no_classes = class.no_classes
    LEFT JOIN pres_student ON student.id_student = pres_student.id_student
    WHERE (class.no_classes = '$class' OR NULL AND pres_student_data = '$data' AND pres_student_id_subject = $id_subject OR NULL)
    GROUP BY student.surname
    ORDER BY student.surname ASC

我想始终显示name_surname,任何其他列都应为NULL或1 喜欢: Name | present | absent | just | late | rel | delegation | note | Donald Trump | 1 | | | | | | | Bush | | | | | | | | Someone | 1 | | | | | | | 等等...

1 个答案:

答案 0 :(得分:1)

您应该将classpres_student表上的限制从WHERE子句移到ON(左联接)。

如果您在具有WHERE的表上的outer join子句中执行限制,则sql引擎会认为您正在执行INNER join

SELECT    student.id_student
        , CONCAT(student.name, ' ', student.surname) AS 'name_surname'
        , pres_student_present
        , pres_student_absent
        , pres_student_justified
        , pres_student_late
        , pres_student_rel
        , pres_student_course
        , pres_student_delegation
        , pres_student_note
FROM      student
LEFT JOIN class
       ON student.no_classes = class.no_classes
      AND class.no_classes   = '$class'
LEFT JOIN pres_student
       ON student.id_student      = pres_student.id_student
      AND pres_student_data       = '$data'
      AND pres_student_id_subject = $id_subject
GROUP     BY student.surname
ORDER     BY student.surname ASC