Mysql中使用where 1=1有什么问题吗

昨天偶然看见一篇文章,提到说如果在mysql查询语句中,使用where 1=1会有性能问题??

这着实把我吸引了,因为我项目中就有不少同事,包括我自己也有这样写的。为了不给其他人挖坑,赶紧学习一下,这样写sql到底有没有性能问题?

where 1=1的使用场景

我们来看下,where 1=1实际是怎么使用的, 先来看一段SQL

<select id="selectCmsCourseList" parameterType="java.util.Map" resultMap="CourseMap">
    SELECT
     a.id,
     a.category_id,
     a.model_id,
     b.*
    FROM
     cms_content a
    LEFT JOIN cms_course b ON a.id = b.id
    WHERE 1=1
    <if test="courseName != null and courseName != ''">
       AND b.course_name like concat(concat("%",#{courseName}),"%")
    </if>
    <if test="disabled != null">
       AND a.disabled = #{disabled}
    </if>
    <if test="categoryId != null">
       AND a.category_id = #{categoryId}
    </if>
</select>

如果用过mybatis的童鞋,看到这段代码应该很熟悉了吧,这里使用where 1=1的作用,就是为了方便后面的条件,能通过if判断,使用AND连接起来,这样即使后面if全部是false,没有参数,这个sql也不会报错。

where 1=1的替换方案

其实上面的这个写法,如果用mybatis,完全可以用where标签来替换,如:

<select id="selectCmsCourseList" parameterType="java.util.Map" resultMap="CourseMap">
    SELECT
     a.id,
     a.category_id,
     a.model_id,
     b.*
    FROM
     cms_content a
    LEFT JOIN cms_course b ON a.id = b.id
    <where>
        <if test="courseName != null and courseName != ''">
           AND b.course_name like concat(concat("%",#{courseName}),"%")
        </if>
        <if test="disabled != null">
           AND a.disabled = #{disabled}
        </if>
        <if test="categoryId != null">
           AND a.category_id = #{categoryId}
        </if>
    </where>
</select>

如果你使用了这个写法,就不存在1=1的问题了,所以也不用纠结,但本着打破砂锅问到底的精神,我们还是得探究一下使用1=1到底有没有性能问题

使用where 1=1有性能问题吗?

先来问问AI

可以看到,AI给到的答复是,基本没有性能问题,更多的是代码风格和可读性!

亲自检测

为了跟进一步测试,我们来写个SQL看看实际性能是否有差别

  1. explain select * from user;

  2. explain select * from user where 1=1;

  3. explain select * from user where id = 8;

  4. explain select * from user where 1=1 and id = 8;

可以看到示例1和示例2, 示例3和示例4,这两组写法,都是有个1=1的区别,但性能都是一样的,因此我们基本可以判定,这个写法,对性能是没有影响的。

总结

如果你在项目中也有使用where 1=1写的SQL,如果从可读性或者代码风格考虑,建议优化掉,但如果担心性能问题,则大可不必过多考虑~

相关推荐
五月茶1 小时前
Maven+SSM+SpringBoot+Mybatis-Plus
spring boot·maven·mybatis
B站计算机毕业设计超人2 小时前
计算机毕业设计SpringBoot+Vue.jst房屋租赁系统(源码+LW文档+PPT+讲解)
vue.js·spring boot·后端·eclipse·intellij-idea·mybatis·课程设计
杰九2 小时前
【环境配置】maven,mysql,node.js,vue的快速配置与上手
java·vue.js·spring boot·mysql·node.js·maven
致奋斗的我们4 小时前
HAProxy介绍与编译安装
linux·汇编·数据库·mysql·青少年编程·haproxy·openeurler
Mr-Apple4 小时前
MySQL的Union和OR查询
android·数据库·mysql
hxung5 小时前
MySQL面试学习
学习·mysql·面试
莳花微语6 小时前
使用MyCAT实现分布式MySQL双主架构
分布式·mysql·架构
he258196 小时前
centOS 7.9 安装JDK MYSQL
java·mysql·centos
夜泉_ly8 小时前
MySQL -安装与初识
数据库·mysql
月光水岸New11 小时前
Ubuntu 中建的mysql数据库使用Navicat for MySQL连接不上
数据库·mysql·ubuntu