题主今天在书写一个查询语句时,因为and问题纠结半天,下面是代码:
<select id="queryPageLoginUsers">
SELECT *
FROM
lbdj_login_key
<where>
<trim prefixOverrides="and">
<if test="keyUser != null and keyUser.trim().toString() != ''">
and key_user LIKE concat('%',#{keyUser},'%')
</if>
<if test="timeType != null and timeType == 1">
and login_time between concat(#{startDate},' 00:00:00') and concat(#{endDate},' 23:59:59')
</if>
<if test="timeType != null and timeType == 2">
and key_send_time between concat(#{startDate},' 00:00:00') and concat(#{endDate},' 23:59:59')
</if>
<if test="loginChannel != null">
and login_channel = #{loginChannel}
</if>
<if test="loginAccount != null and loginAccount.trim().toString() != ''">
and account_name = #{loginAccount} or login_account = #{loginAccount}
</if>
</trim>
</where>
ORDER BY login_time desc, key_send_time desc
</select>
开始时,将“and”都写入语句的后方
<if test="keyUser != null and keyUser.trim().toString() != ''">
key_user LIKE concat('%',#{keyUser},'%') and
</if>
这就导致后面条件为null时,and不会被消除,于是引入,问题就此解决!
注意:写语句时尽量不要加入多余的括号,今天就是被“()”整懵逼了,由于一些函数本身带有括号,容易与自己书写的括号造成混淆。
写sql语句前,一定要将原始语句执行一遍。