在mybatis xml编写sql语句时,同时使用AND和OR注意

SQL查询优化:理解AND和OR操作符的正确使用
本文通过一个SQL查询示例解释了在使用AND和OR组合条件时,为何需要使用小括号来确保正确的逻辑运算。在搜索框中同时搜索两个字段时,如果不加括号可能导致搜索结果错误。示例展示了如何在IF标签中正确地应用括号,以避免搜索逻辑出错,从而保证查询的准确性。
当AND和OR同时使用时,要把OR的条件使用小括号括起来
例如下边这个例子,在第一个if标签中同时使用了AND和OR,
想要实现同一个搜索框搜索两个字段,如果不加括号则会搜索内容出错
<select id="selectAll" parameterType="com.jh.store.entity.criteris.GoodsCriteria" resultType="com.jh.store.entity.domain.GoodsInfor">
    select
    t_bus_goods.id,
    goods_name,orig_price,
    t_ent_store.store_name,
    t_bus_goods.good_type_name,
    consum_start_date,
    pic_url,
    max_count,
    share_num,
    start_date,
    during,
    t_bus_goods.end_date,
    is_show,
    share_status,
    sex_limit,
    male_count,
    female_count,
    time_end_logic,
    t_bus_goods.description
    from
    t_bus_goods,t_ent_store
    WHERE
    t_bus_goods.store_id=t_ent_store.id
        <if test="null!= name">
            and (goods_name like "%"#{name}"%" or store_name like "%"#{name}"%")
        </if>
    <if test="-3 != is_check">
        and share_status=#{is_check}
    </if>
    <if test="null!=onetime">
        and t_bus_goods.consum_start_date <![CDATA[ >= ]]> #{onetime}
    </if>
    <if test="null!=twotime">
        and t_bus_goods.consum_start_date <![CDATA[ <= ]]> #{twotime}
    </if>
        <if test="null!=onlytime">
            and t_bus_goods.consum_start_date <![CDATA[ >= ]]> #{onlytime}
            and t_bus_goods.consum_start_date <![CDATA[ < ]]> #{onlytime2}
        </if>

    ORDER BY consum_start_date DESC
    </select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值