mybatis 写 SQL 使用了 where 1=1 来简化多条件拼接的写法,案例如下,借此聊聊多条件拼接的常见的一些写法以及 where 1=1 是否存在性能影响。<select id="" parameterType = "">
SELECT * FROM users
WHERE 1=1
<if test="userName != null ">
AND user_name = #{userName}
</if>
<if test="userAge != null ">
AND user_age = #{userAge }
</if>
<if test="userSex!= null ">
AND user_sex = #{userSex}
</if>
</select>
<select id="" parameterType = "">
SELECT * FROM users
WHERE 1=1
<if test="userName != null ">
AND user_name = #{userName}
</if>
<if test="userAge != null ">
AND user_age = #{userAge }
</if>
<if test="userSex!= null ">
AND user_sex = #{userSex}
</if>
</select>
mybatis 提供 <where> 标签,<where> 标签只有在一个以上的if条件有值的情况下才去插入WHERE子句。若AND 或 OR 前没有有效语句,where 元素会将它们去除。<select id="" parameterType = "">
SELECT * FROM users
<where>
<if test="userName != null ">
AND user_name = #{userName}
</if>
<if test="userAge != null ">
AND user_age = #{userAge }
</if>
<if test="userSex!= null ">
AND user_sex = #{userSex}
</if>
</where>
</select>
where 1=1 和 <where> 标签两种写法前者性能损耗在 SQL查询性能优化,后者在于 SQL 语句动态生成 。下面我们来具体分析一下:SELECT VERSION(); 5.7.44 # 数据构造 SQL CREATE TABLE IF NOT EXISTS t_user ( id INT not null auto_increment primary key comment '自增ID', name varchar(20) comment '姓名', age tinyint comment '年龄' )ENGINE = INNODB; INSERT INTO t_user ( NAME, age ) VALUES ( '张三', 18 ),( '李四', 19 ),( '王五', 20 ),( '司总', 21 );
SQL查询性能优化 会将 1=1 部分优化掉,并不会影响索引,但网上有部分资料说在低版本中有一定影响,所以需要稍微留意一下。# 注:需要选中一起执行可以查看到优化后的 SQL
explain select * from t_user where 1=1 AND name = '张三';
show warnings;
# 优化后的 SQL
/* select#1 */ SELECT
`mydatabase`.`t_user`.`id` AS `id`,
`mydatabase`.`t_user`.`name` AS `name`,
`mydatabase`.`t_user`.`age` AS `age`
FROM
`mydatabase`.`t_user`
WHERE
(
`mydatabase`.`t_user`.`name` = '张三')
SQL 可以看到, 1=1 部分已经被查询优化器优化掉,所有对整体的性能影响并不大。# 性能对比 select * from t_user where 1=1 AND name = '张三' > OK > 查询时间: 0.046s select * from t_user where 1=1 > OK > 查询时间: 0.046s
where 1=1 在 MySQL 中服务器层由查询优化器进行处理,<where> 标签在动态构建 SQL 中处理,但性能也无很大影响,因为本质并不是很复杂的动态 SQL 生成。where 1=1 和 <where> 标签是多条件拼接的两种常见写法,性能层面而言并没有较大的影响,具体选择何种写法可以根据团队的规范决定。以上就是深入探究MySQL中使用where 1=1是否存在性能影响的详细内容,更多关于MySQL where 1=1性能影响的资料请关注插件窝其它相关文章!