mybatis 条件查询sql问题

<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">

    select * from user where

        <if test="username != null">

           username=#{username}

        </if>

        

        <if test="username != null">

           and sex=#{sex}

        </if>

</select>

这样写我们可以看到,如果 sex 等于 null,那么查询语句为 select * from user where username=#{username},但是如果usename 为空呢?那么查询语句为 select * from user where and sex=#{sex},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句

动态SQL:if+where 语句

<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">

    select * from user

    <where>

        <if test="username != null">

           username=#{username}

        </if>

        

        <if test="username != null">

           and sex=#{sex}

        </if>

    </where>

</select>

这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。

用 foreach 来改写 select * from user where id=1 or id=2 or id=3

<select id="selectUserByListId" parameterType="com.ys.vo.UserVo" resultType="com.ys.po.User">

    select * from user

    <where>

        <!--

            collection:指定输入对象中的集合属性

            item:每次遍历生成的对象

            open:开始遍历时的拼接字符串

            close:结束时拼接的字符串

            separator:遍历对象之间需要拼接的字符串

            select * from user where 1=1 and (id=1 or id=2 or id=3)

          -->

        <foreach collection="ids" item="id" open="and (" close=")" separator="or">

            id=#{id}

        </foreach>

    </where>

</select>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值