mybatis 动态查询括号的问题


我想实现一个查询,sql语句如下


 select * from user where ( id like '%1%' or name like '%foo%') and active=1

其中id,name可以是动态的,可以为null
我写的是这样的


 <select id="selectByUser" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
<where>
<if test="id != null || name !=null">
    (
    <if test="id != null">
    <bind name="id" value="'%' + id + '%'" />
     `id` like #{id,jdbcType=INTEGER}
    </if>
    <if test="name != null">
    <bind name="name" value="'%' + name + '%'" />
        or `name` like #{name,jdbcType=VARCHAR} 
    </if>
    ) and 
</if>
active=1
</where>
</select>

可是当id为空的时候就有错误:


 select * from user where ( or name like '%foo%' ) and active =1

因为加了括号<where>标签没有去掉'or'关键字请问有什么方法可以实现这个sql功能

sql mybatis java

吴克的叔叔葛炮 8 years, 7 months ago

最简单的办法,就是"("的后面加上1=0
不过像@毛宇鹏V说的用 trim 也是可以实现的,而且更加合理

Meiko answered 8 years, 7 months ago

可以使用<trim>标签

BAHLM answered 8 years, 7 months ago

Your Answer