0

I am creating attendance management system for a school in php and mysql. I have 3 tables in database these are:

1. Students
id 
student_name
class

2. subjects
id
subjects


3. attendances
id
subject_id
student_id
attend (boolean)
today_date

I am only storing students who are attending classes in attendance table.

I want grab the list of all students (which are in or not in attendance table) who are attend or not for a particular class, date, and subject.

Like;

Attendance for Class - X(Physics) on 18-08-2017

    ______________________________
    | Student Name  | Attendance |
    ------------------------------
    | Foo           |     0      |
    | Bar           |     1      |
    | Baz           |     0      |
    | Qux           |     1      |
    ------------------------------

I was trying queries

SELECT s.id,s.student_name, a.attend as attend 
FROM attendances as a 
INNER JOIN students as s on s.id = a.student_id 
WHERE s.class = 'X'
AND a.subject_id = 3 
AND a.date = '2017-08-18' 

But I am not getting the result I want. I am sure there will be some better and simple way to achieve this which I am missing there, because I haven't use SQL in this way before.

2 Answers 2

1

Below query might help you to achieve desired result:

SELECT s.id,s.student_name, IFNULL(a.attend, 0) as attend FROM students as s LEFT JOIN attendances as a on s.id = a.student_id WHERE s.class = 'X' AND a.subject_id = 3 AND a.date = '2017-08-18' 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but this is giving only students which are available in attendances table, but I want all students which are available in attendances or not.
Use RIGHT JOIN.
I tried that but same result. I think it's because of these conditions "a.subject_id = 3 AND a.date = '2017-08-18'" it is giving this result. Is there any way to manipulate these conditions.
1
SELECT s.id,s.student_name, a.attend as attend FROM attendances as a 
RIGHT JOIN students as s on s.id = a.student_id AND a.subject_Id=3 
AND a.date='2017-08-18' WHERE s.class = 'X'

2 Comments

Please add formatting to your code (at least by highlighting your code and hitting Ctrl + K on your keyboard)
No problem, I saw that this was your first answer and just wanted to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.