简体   繁体   中英

Left Join With Null value Table

I was using this query to connect my student table and attendance table,
My Problem is, sometimes, attendance table has no value.
It's not returning any value.

<?php
if($_SERVER['REQUEST_METHOD']=="POST"){
    include('include/connection.php');
    showData();
}

function showData(){
    global $connect;
    $teacher_id = $_POST['teacher_id'];
    $subject_id = $_POST['subject_id'];
    $date = $_POST['date'];
    $query ="
SELECT s.student_name
     , s.student_number
     , s.student_section
     , s.subject_id
     , s.fingerprint_id
     , s.teacher_id
     , a.status
  FROM tbl_student s
  LEFT 
  JOIN tbl_attendance a 
    on s.subject_id=a.subject_id
 WHERE s.subject_id = '$subject_id' 
   and a.date='$date' 
   and s.teacher_id = '$teacher_id';";
    $result =mysqli_query($connect,$query);
    $number_of_rows = mysqli_num_rows($result);
    $temp_array=array();

    if($number_of_rows>0){
        while($row=mysqli_fetch_assoc($result)){
            $temp_array[]=$row;     
        }
    }
    header('Content-Type: application/json');
    echo json_encode(array("student"=>$temp_array));
    mysqli_close($connect);
}


?>

What I want to achive is even if attendance table has no value,
I can still see the student fields.
Is it even possible with SQL query? Thanks

SELECT student.student_name,student.student_number,student.student_section,student.subject_id,student.fingerprint_id,student.teacher_id,attendance.status
        FROM tbl_student student
        LEFT JOIN tbl_attendance attendance on student.subject_id=attendance.subject_id and attendance.date='$date' 
        WHERE student.subject_id='$subject_id' and student.teacher_id='$teacher_id';

Try above code.Hope this will helps. As you had made condition on student table using attendance.date='$date' on WHERE clause it exclude that record which are not satisfy this condition. So instead of where i had put that condition through ON clause on LEFT JOIN . This will achieve your goal.

You have to move the fields of table attendance from where to the on condition:

$query ="SELECT student.student_name,student.student_number,student.student_section,student.subject_id,student.fingerprint_id,student.teacher_id,attendance.status
    FROM tbl_student student
    LEFT JOIN tbl_attendance attendance on student.subject_id=attendance.subject_id and attendance.date='$date'
    WHERE student.subject_id='$subject_id'  and student.teacher_id='$teacher_id';";

Because first the join Statement will be executed and then the where, if you access the table tbl_attendance in where ans all the columns are null, they will filtered out.

Hint: read about prepared Statements to provide SQL-injection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM