简体   繁体   中英

optional where clause condition in mysql

I am working on a project where I load a list of students depending on the date selected and the teacher chosen from a dropdown.The list contains those students data whose class teacher is the teacher selected. Now i am using the following query:

select s.studentcode,s.studentname,a.attdate,if(a.period='01' or 
a.period='AM',a.status,'') as attAM,if(a.period='PM',a.status,'') as attPM 
from tblstudent s left join tblattendance a on s.studentcode=a.studentcode 
where s.classcode='10002' and a.attdate='2014-04-11'

Now the problem with the above is query is that if i chose some date like 2014-04-15 then as attendance is not marked for this date then no record is found,but i want that the student list is always displayed and if attendance is marked for that date it should be displayed accordingly else those fields will be blank

在此处输入图片说明

The above screenshot is displaying the list which I want.Now the field AM should be blank if attendance for that date is not marked and if it is marked it should contain the corresponding attendance

Move your AND a.attdate = '2014-04-11' to join's ON() clause so if date is not present it still returns the records for s.classcode = '10002' and a.attdate column will be null in the result set,where filter is applied to whole resultset where as using additional condition in join will filter the records from right table ie tblattendance not on whole resultset

SELECT 
  s.studentcode,
  s.studentname,
  a.attdate,
  IF(
    a.period = '01' 
    OR a.period = 'AM',
    a.status,
    ''
  ) AS attAM,
  IF(a.period = 'PM', a.status, '') AS attPM 
FROM
  tblstudent s 
  LEFT JOIN tblattendance a 
    ON (s.studentcode = a.studentcode AND a.attdate = '2014-04-11')
WHERE s.classcode = '10002' 

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