今天做项目遇到一个奇怪的问题,特此记录一下:
应用场景介绍:
有一张班级学生表(student):一共有三个学生,id分别是1,2,3,姓名分别是a,b,c
有一张出勤表(attendance):有两条记录关联班级表的外键id(pid)分别是1,3,出勤状态(status)分别是1:出勤,2:请假
因为没有b的出勤记录,所b默认是未出勤
要求:查询出不同状态的学生,
参数类型:传进来的实体类中status属性是String
前端可传来四种参数:0(未出勤),1(出勤),2(请假),null(不根据出勤状态查询)
-- 我在xml中系的sql文是
select *
from student stu
left join attendance att
on stu.id = att.pid
<where>
<if test="pbj.status != null">
<choose>
<when test="pbj.status != '0'">
and stu.status = #{pbj.status}
</when>
<otherwise>
and stu.status is null
</otherwise>
</choose>
</if>
</where>
执行结果:
1.传进来status = null
执行的是sql没有where后的条件,这是正常的
2.传进来status = “1” 或者"2"
执行的sql中where后面是 stu.status = ‘1’ 或者 stu.status = ‘2’;这也是正常的
3.我传入status = “0”
执行的结果居然是:where stu.status = ‘0’;
直接给我干蒙了 ,
解决
拼接sql文判断status的值时不需要加单引号
select *
from student stu
left join attendance att
on stu.id = att.pid
<where>
<if test="pbj.status != null">
<choose>
<when test="pbj.status != 0">
and stu.status = #{pbj.status}
</when>
<otherwise>
and stu.status is null
</otherwise>
</choose>
</if>
</where>