sql where 1 = 1的原理

where 1=1      这个条件始终为True,在不定数量查询条件情况下,1=1可以很方便的规范语句。


主要体现在mybatis的.xml查询语句中

<select id="countByQuery" parameterType="com.mtoliv.XXX" resultMap="BaseResultMap">
    select count(*) count_sum from v_alert_device where 1=1 
      <if test="customerId != null">
        and customer_id = #{customerId,jdbcType=VARCHAR} 
      </if>
      <if test="alertTypeId != null">
        and alert_type_id = #{alertTypeId,jdbcType=INTEGER} 
      </if>   
      order by count_sum desc LIMIT 10
  </select>

①加了where 1=1,并且假设customerId和alertTypeId有值那么这条话的sql语句为:

select count(*) count_sum from v_alert_device where 1=1 and customer_id = 'hahaha' and alert_type_id = 123 order by count_sum desc LIMIT 10


②不加where 1=1,并且假设customerId和alertTypeId没有值那么这条话的sql语句为:

select count(*) count_sum from v_alert_device where order by count_sum desc LIMIT 10

那么就会报错。

加了where 1=1,并且假设customerId和alertTypeId没有值那么这条话的sql语句为:

select count(*) count_sum from v_alert_device where 1=1 order by count_sum desc LIMIT 10

则会返回table中的根据count_sum 降序的前十条值。


由此可以看出,where 1=1 这种写法 虽然给程序开发人员带来不便,还要避免sql注入的问题。

但 where 1=1 这种写法 也会给程序编写增加了方便。




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值