使用动态sql查询数据库,查询出来的数据比预期的要少

本文讨论了在SQL查询中如何通过修改条件语句,避免对null值进行不必要的空字符串判断,以提高查询性能。针对前端Vue应用,当用户输入不传参数时,通过修改`if`标签的条件,确保只在非空字符串时执行模糊搜索。
摘要由CSDN通过智能技术生成

在这里插入图片描述含有3个可选传递的参数,前端未传入参数,则默认为空字符串’ '(前端使用的是Vue)
在这里插入图片描述
查询出来的数据只有7条
在这里插入图片描述

<select id="selectTotal" resultType="java.lang.Integer">
    select count(*) from b_users
    <where>
      <if test="userName!=null">
        user_name like concat('%', #{userName}, '%')
      </if>
      <if test="userNickname!=null">
        and user_nickname like concat('%', #{userNickname}, '%')
      </if>
      <if test="userTelNumber!=null">
        and user_tel_number like concat('%', #{userTelNumber}, '%')
      </if>
    </where>
  </select>

改为

<select id="selectTotal" resultType="java.lang.Integer">
    select count(*) from b_users
    <where>
      <if test="userName!=null and userName!=''">
        user_name like concat('%', #{userName}, '%')
      </if>
      <if test="userNickname!=null and userNickname!=''">
        and user_nickname like concat('%', #{userNickname}, '%')
      </if>
      <if test="userTelNumber!=null and userTelNumber!=''">
        and user_tel_number like concat('%', #{userTelNumber}, '%')
      </if>
    </where>
  </select>

<if>便签有一个必填的属性test,test的属性值是一个符合OGNL要求的判断表达式,
表达式的结果可以是true或者false,初次之外所有的的非0值都为true,只有0为false。
且有如下规则:
1.判断条件property!=null或者property==null:适用于任何类型的字段,用于判断属性值是否为空
2.判断条件property!=''或者property=='':仅适用于String类型的字段,用于判断是否为空字符串
3.and和or:当有多个判断条件时,适用and或or进行连接,嵌套的判断可以适用小括号分组。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Morant0214

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值