简体   繁体   English

MySQL-JOIN操作多个表

[英]MySQL - JOIN Operation Multiple Tables

I am creating an Online Attendance System, and my problem is around a query below not bringing back the correct data. 我正在创建一个在线考勤系统,而我的问题出在下面的一个查询中,未带回正确的数据。

I am looking to bring back a Student ID, Class ID and the Attendance Status EG Present Late or Absent of that class. 我希望带回学生ID,班级ID和该班迟到或缺席的出勤状态EG。

If attendance has been taken, then the query run's fine. 如果已出席,则查询运行正常。 However, if no attendance has been taken the query returns an empty set. 但是,如果没有参加,查询将返回一个空集。

I am looking to still return all the data but have 'null' or anything in the 'Attendance Status' column, If attendance hasn't been taken. 我仍希望返回所有数据,但“出勤状态”列中为“空”或任何内容(如果未参加)。

This is the query : 这是查询 MySQL查询

And it bring back these results if attendance has been taken for the class: 如果参加了课堂,它将带回这些结果

MySQL结果

However, If attendance hasn't been taken, then it will just return an empty set. 但是,如果未参加会议,它将仅返回一个空集。 What I would like is for in the attendance column it print 'null' or anything to make sure some data still comes back. 我想要的是在出勤列中将其打印为“ null”或任何可确保仍返回某些数据的内容。

At minimum I still need the Class and Student ID. 至少我仍然需要班级和学生证。 I think it may need a JOIN , I just can't get my head around it. 我认为它可能需要加入 ,我无法理解。

You should use the proper syntax of JOINS! 您应该使用正确的JOINS语法! that can cause a lot of problems and it is harder to understand. 这可能会导致很多问题,并且很难理解。

What you need is a LEFT JOIN which can be used using(+) after the condition of the table you want to left join to - DON'T DO IT. 您需要一个左联接,您可以在要离开联接的表的条件之后使用(+)来使用-请勿这样做。

Your query should be: 您的查询应为:

 SELECT class.class_id as 'Class_ID',
        student.Student_ID as 'Student_ID',
        case when attendence.attendence_status is null then 'Not Present' else attendence.attendence_status end as 'attendence_status'
FROM Student
INNER JOIN Student_Has_Class ON(student_has_class.student_id = student.student_id)
INNER JOIN class ON(class.class_id = student_has_class.class_id)
INNER JOIN Subject ON(class.subject_id = subject.subject_id)
LEFT JOIN Attendence on(attendence.class_id = class.class_ID
                        AND attendence.student_id = student.student_id)
WHERE NOW() between class.class_start_timestamp and class.class_end_timestamp
AND Student.student_id like '1'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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