<select id="daoFactory" parameterType="Map" resultType="Map">
select u.sex,u.name
from user u
where 1 =1
<if test="sex !=null and sex!= '' ">
and u.sex= #{sex}
</if>
<if test="name !=null and name != ''">
and u.name = #{name}
</if>
</select>
就一段很简单的查询sql , 在工作中常见的用法就是where后面加上一个 1=1,
好奇就问, 为什么嘞?
原因其实很简单, 如下,没有1=1的语句
<select id="daoFactory" parameterType="Map" resultType="Map">
select u.sex,u.name
from user u
where
<if test="sex !=null and sex!= '' ">
and u.sex= #{sex}
</if>
<if test="name !=null and name != ''">
and u.name = #{name}
</if>
</select>
对比一下, 发现好像就少了一行sql, 没啥影响
但是, 并不是那么简单的
当 下面的两个条件不论成立还是不成立的时候,
SQL都会报错了
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/07a51cf9097e09b492e4611915ffc80f.png)
这样的操作肯定不对啊
而且, 当其中一个条件,成立的时候的SQL是
…
当我传入的name为正确的值的时候的sql
这又是什么神仙操作…
所以where 1=1的作用是不是很明显了,
防止傻缺的SQL出现,
对于 and 的出现进行占位, 当没有and条件的时候就是相当于
select name from u_user where 1=1
做全表扫描,
这样又会有一些性能的问题, 应该在加上一些不会为空的条件在1=1后面, 并且在这些必须存在的条件上加上索引, 方便做到在全表扫描的时候的效率问题