[英]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.