mybatis and和or的组合查询

在mybatis中涉及到和、或者的查询需要注意,一招不慎,会导致查询出来的结果不准确。

究其原因,是and优先级高于or。凡是查询中涉及到or,需要将or 条件和与之并肩查询的条件用括号括起来。

来看错误的写法:

select
  <include refid="Base_Column_list" />
from tb_user
where 1=1 AND username=#{map.username}
<if test="map.type!=null and map.type!=">
   AND type like concat (%,#{map.type},%) 
</if>
<if test="map.eqip!=null and map.eqip!=">
   OR eqip like concat (%,#{map.eqip},%)
</if>
<if test="map.startTime!=null and map.startTime!=">
	<![CDATA[   and DATE_FORMAT(login_date, %Y-%m-%d)>=  DATE_FORMAT(#{map.startTime}, %Y-%m-%d)   ]]>
</if>
<if test="map.endTime!=null and map.endTime!=">
	<![CDATA[  and DATE_FORMAT(login_date, %Y-%m-%d) <= DATE_FORMAT(#{map.endTime}, %Y-%m-%d)    ]]>
</if>

ORDER BY login_date desc

查询类型为Y,并且设备登录时间在2022.9.20和2022.9.23之间的数据,执行后却把2022.9.24的数据也查询出来了,显示是错误的。

正确的写法:

select
  <include refid="Base_Column_list" />
from tb_user
where 1=1 AND user_name=#{map.username}
<if test="map.type!=null and map.type!= and map.eqip!=null and map.eqip!=">
   AND (type like concat (%,#{map.type},%)  OR eqip like concat (%,#{map.eqip},%))
</if>
<if test="map.startTime!=null and map.startTime!=">
	<![CDATA[   and DATE_FORMAT(login_date, %Y-%m-%d)>=  DATE_FORMAT(#{map.startTime}, %Y-%m-%d)   ]]>
</if>
<if test="map.endTime!=null and map.endTime!=">
	<![CDATA[  and DATE_FORMAT(login_date, %Y-%m-%d) <= DATE_FORMAT(#{map.endTime}, %Y-%m-%d)    ]]>
</if>

ORDER BY login_date desc

重点在这里

AND (type like concat (%,#{map.type},%)  OR eqip like concat (%,#{map.eqip},%))

修改后重新执行,终于得到正确的结果了:

经验分享 程序员 微信小程序 职场和发展