参考:https://blog.youkuaiyun.com/xcliang9418/article/details/79146114
where 1=1;有什么用?在SQL语言中,这个条件始终为True,写这一句话就跟没写一样。select * from table where 1=1与select * from table完全没有区别,其目的就是使 where 的条件永远为true,得到的结果就是未加约束条件的结果。
在查询条件数量不确定的条件情况下,使用 where 1=1可以很方便的规范语句。例如一个查询中可能有name,age,height,weight等不确定数量的约束条件,那么使用
<sql id="whereSQL">
WHERE 1 = 1
AND b = #{a.b}
<if test="a.startDate != null">
<![CDATA[
AND `date` >= #{a.startDate}
]]>
</if>
<if test="a.endDate != null">
<![CDATA[
AND `date` <= #{a.endDate}
]]>
</if>
</sql>
总结:
- 如果不写1=1,那么
在每一个不为空的查询条件面前,都必须判断有没有where字句
,哪里该加where,哪里该加and/or
- 如果用上 where 1=1 之后,就不存在这样的问题,条件是 and 就直接and,是or就直接接 or