<where> 标签的作用
where标签帮助我们自动的移除了第一个<if>标签内的AND或OR。但是,第二个之后的<if>标签内,必须有AND或OR。
如果没有一个条件符合,则返回所有条目,where不起作用。
举个例子
<select id="idName" parameterType="returnDto" resultType="java.lang.Integer">
select count(id) from table t
where 1 = 1
<if test="title != null and title != '' ">
AND title = #{title}
</if>
<if test="name !=null and name != '' ">
AND name= #{name}
</if>
上面的代码就是查询符合条件的总条数。在mybatis中常用到if标签判断where子句后的条件,为防止首字段为空导致sql报错。当遇到多个查询条件,使用where 1=1 可以很方便的解决我们条件为空的问题.在mysql进行解析优化的时候会处理1 = 1这类无意义的条件将会被优化器所优化掉。这样会增加优化器处理时间。
改进后
<select id="idName" parameterType="returnDto" resultType="java.lang.Integer">
select count(id) from table t
<where>
<if test="title != null and title != '' ">
title = #{title}
</if>
<if test="name !=null and name != '' ">
AND name = #{name}
</if>
</where>
</select>