[英]Left Join With Null value Table
我正在使用此查询来连接学生表和出勤表,
我的问题是,有时候出勤表没有价值。
它没有返回任何值。
<?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);
}
?>
我想要达到的是即使考勤表没有价值,
我仍然可以看到学生领域。
SQL查询甚至有可能吗? 谢谢
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';
试试上面的代码,希望这会有所帮助。 由于您已经在WHERE
子句中使用attendance.date='$date'
在学生表上设置了条件,因此排除了不满足此条件的记录。 因此,而不是我通过LEFT JOIN
ON
子句将该条件放在何处。 这将实现您的目标。
您必须将表attendance
的字段从where
移至on
条件:
$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';";
因为首先将执行join语句,然后将执行where语句,因此,如果在其中ans所有tbl_attendance
null的位置访问表tbl_attendance
,则它们将被过滤掉。
提示:了解准备好的语句以提供SQL注入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.