mybatis动态拼接只查询某一字段值为null的所有记录

今天做项目遇到一个奇怪的问题,特此记录一下:

应用场景介绍:

​ 有一张班级学生表(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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值