[英]SQL Query Left Join Tables
我確定昨天可以實施,如果其他表沒有價值,請使用LEFT JOIN
。
我現在的問題是,如果不確定哪個表具有價值,哪個表具有價值,該怎么辦。
我已經試過這個查詢。
$query ="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 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';";
但是不幸的是,如果我的記錄表為空,它將不會顯示任何內容。
我想達到的目標是
如果table_record
是空的, tbl_attendance
不是,它會顯示在記錄tbl_attendance
,
如果table_attendance
是空的, table_record
不是,它會顯示在table_record記錄。
將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。 您可以在RIGHT JOIN部分中將所有record。*字段替換為NULL:
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
;
只需將“左聯接”更改為“完全外聯接”
SELECT *
FROM tbl_Students S
FULL OUTER JOIN tbl_Attendance A
ON S.StudentID = A.AttendanceStudentID
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.