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功能

阅读 18.9k
4 个回答

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

可以使用<trim>标签

新手上路,请多包涵

可以这样使用

<where>
    ( 
        <trim prefixOverrides="AND |OR">
            条件
        </trim>
    )
</where>

我今天也遇到了这个问题。

新手上路,请多包涵
            <choose>
                <when test='searchType != null and (customName != null or operatorDepartment != null)'>
                    and (
                    <trim prefixOverrides="OR">
                        <if test="customName != null">
                            OR  custom_name like concat("%",#{customName},"%")
                        </if>
                        <if test="operatorDepartment != null">
                            OR distr_str like concat("%",#{operatorDepartment},"%")
                        </if>
                    </trim>
                    )
                </when>
                <otherwise>
                    <if test="customName != null">
                        and custom_name like concat("%",#{customName},"%")
                    </if>
                    <if test="operatorDepartment != null">
                        and distr_str like concat("%",#{operatorDepartment},"%")
                    </if>
                </otherwise>
            </choose>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题