du6jws6975 2017-03-07 07:29
浏览 122
已采纳

左连接Null值表

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

  • 写回答

2条回答 默认 最新

  • dow98764 2017-03-07 07:32
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?