SQL查询左连接表

时间:2017-03-08 07:35:13

标签: mysql sql

我肯定会在昨天实施并且如果另一个表没有值,则使用orange 我现在的问题是,如果您不确定哪个表具有值以及哪个表具有值,该怎么办?

我试过这个查询。

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中显示记录。

2 个答案:

答案 0 :(得分:0)

将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部分中替换所有带有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
; 

答案 1 :(得分:0)

只需将“Left JOIN”更改为“FULL OUTER JOIN”

           SELECT * 
             FROM tbl_Students S
  FULL OUTER JOIN tbl_Attendance A
               ON S.StudentID = A.AttendanceStudentID