简体   繁体   English

mysql中的可选where子句条件

[英]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 现在上面的问题是查询,如果我选择某个日期,例如2014-04-15,则由于未标记出勤这个日期,则找不到任何记录,但是我希望始终显示学生列表,并且出勤率是标记为该日期,则应相应显示,否则这些字段为空白

在此处输入图片说明

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 上面的屏幕截图显示了我想要的列表。如果未标记出该日期的出勤率,则AM字段应为空白,如果被标记,则其中应包含相应的出勤率

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 将您的AND a.attdate = '2014-04-11'到加入的ON()子句中,因此,如果不存在日期,它仍将返回s.classcode = '10002'的记录,并且a.attdate列的结果为null设置,其中将过滤器应用于整个结果集,其中在tblattendance使用附加条件将过滤来自右表的记录,即tblattendance不在整个结果集上

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' 

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

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