需求:一个搜索框同时对userId和title进行模糊查询。
第一次:
<where><if test="disId!=null and disId != '' " >and DIS_ID = #{disId}</if><if test="category!=null" >and CATEGORY = #{category}</if><if test="userId!=null" >and USER_ID like CONCAT('%',#{userId},'%' ) </if><if test="userType!=null" >and USER_TYPE = #{userType}</if><if test="title!=null" >and TITLE like CONCAT('%',#{title},'%' ) </if></where>
![日志里的SQL是这样的](https://img-/0707230448959)这种方式查询时,日志里的SQL如上所示,会导致对2个字段进行AND查询,只有都具有相同关键字时才可以被查出来。*
第二次:
*
<trim prefix="where" prefixOverrides="and \ or"><if test="disId!=null and disId != '' " >and DIS_ID = #{disId}</if><if test="category!=null" >and CATEGORY = #{category}</if><if test="userId!=null" >and USER_ID like CONCAT('%',#{userId},'%' ) </if><if test="userType!=null" >and USER_TYPE = #{userType}</if><if test="title!=null" >and TITLE like CONCAT('%',#{title},'%' ) </if></trim></select>
在日志中会出现如上图所示的错误,很明显,userId字段前多了“and”,TITLE前应该为“or”。
第三次:
“
`from QUESTION<trim prefix="where" prefixOverrides="and \ or"><if test="disId!=null and disId != '' " >DIS_ID = #{disId}</if><if test="category!=null" >CATEGORY = #{category}</if><if test="userId!=null" >USER_ID like CONCAT('%',#{userId},'%' ) </if><if test="userType!=null" >USER_TYPE = #{userType}</if><if test="title!=null" >or TITLE like CONCAT('%',#{title},'%' ) </if></trim></select>
trim标签中不要条件字段,只在 第一个以后的字段前加“or”即可。
好了!