將LEFT JOIN更改爲FULL OUTER JOIN,改編WHERE子句並讓我們知道它是如何發生的。
SELECT
record.student_name,
coalesce(record.student_id, attendance.student_number),
record.student_finger,
record.student_section,
record.activity_type,
record.activity_title,
record.score,
record.teacher_id,
record.activity_id,
record.subject_id,
attendance.status,
attendance.date
FROM tbl_record record
FULL OUTER JOIN tbl_attendance attendance on record.student_id=attendance.student_number
WHERE (record.subject_id='$subject_id' and record.teacher_id='$teacher_id'
and record.student_section='$section')
or record.subject_id is null;
這是一個草稿MySql版本,其中FULL OUTER JOIN不受支持。您可以替換所有記錄*同在右邊用NULL字段JOIN部分:
SELECT
record.student_name,
record.student_id,
record.student_finger,
record.student_section,
record.activity_type,
record.activity_title,
record.score,
record.teacher_id,
record.activity_id,
record.subject_id,
attendance.status,
attendance.date
FROM tbl_record record
LEFT JOIN tbl_attendance as attendance on
record.student_id = attendance.student_number
WHERE (record.subject_id='$subject_id' and record.teacher_id='$teacher_id'
and record.student_section='$section')
UNION
SELECT
record.student_name,
attendance.student_number,
record.student_finger,
record.student_section,
record.activity_type,
record.activity_title,
record.score,
record.teacher_id,
record.activity_id,
record.subject_id,
attendance.status,
attendance.date
FROM tbl_record as record
RIGHT JOIN tbl_attendance as attendance on
record.student_id = attendance.student_number
WHERE record.subject_id is null
;
爲此你需要'FULL OUTER JOIN' 。但是這沒什麼意義,因爲不會有任何主題,老師或部分信息,所以當您嘗試過濾它時(在您的「where」中),您將無法獲得結果。如果你想得到老師X的報告,但'tbl_record'裏沒有什麼東西,你期望什麼回來?看起來你有一個數據完整性問題 –
也許我應該只考慮tbl_record。 –
表模型'事物'或'活動'。每張桌子在這裏代表什麼?一個名爲'tbl_record'的表格讓我不知道該表是什麼意思。 'tbl_attendance'確實給了我一個線索。如果你在tbl_attendance上有一個給定student_number的記錄,那該學生的號碼怎麼不在'tbl_record'中?你必須以某種方式無形中發明'student_id'值。您需要做的是以非技術性語言理解需求,即提出問題。你可能會發現這個問題毫無意義。 –