当前位置:网站首页>新来的同事问我 where 1=1 是什么意思???
新来的同事问我 where 1=1 是什么意思???
2022-06-11 02:07:00 【Java知音_】
点击关注公众号,实用技术文章及时了解
写在前面
新的同事来之后问我where 1=1 是什么有意思,这样没意义啊,我笑了。今天来说明下。
where 1=1
先来看一段代码
<select id="queryBookInfo" parameterType="com.ths.platform.entity.BookInfo" resultType="java.lang.Integer">
select count(id) from t_book t where 1=1
<if test="title !=null and title !='' ">
AND title = #{title}
</if>
<if test="author !=null and author !='' ">
AND author = #{author}
</if>
</select>上面的代码很熟悉,就是查询符合条件的总条数。在mybatis中常用到if标签判断where子句后的条件,为防止首字段为空导致sql报错。
没错 ,当遇到多个查询条件,使用where 1=1 可以很方便的解决我们条件为空的问题,那么这么写 有什么问题吗 ?
网上有很多人说,这样会引发性能问题,可能会让索引失效,那么我们今天来实测一下,会不会不走索引
实测
title字段已经加上索引,我们通过EXPLAIN看下
EXPLAIN SELECT * FROM t_book WHERE title = '且在人间';
EXPLAIN SELECT * FROM t_book WHERE 1=1 AND title = '且在人间';
对比上面两种我们会发现 可以看到possible_keys(可能使用的索引) 和 key(实际使用的索引)都使用到了索引进行检索。
结论
where 1=1 也会走索引,不影响查询效率,我们写的sql指令会被mysql 进行解析优化成自己的处理指令,在这个过程中1 = 1这类无意义的条件将会被优化。使用explain EXTENDED sql 进行校对,发现确实where1=1这类条件会被mysql的优化器所优化掉。
那么我们在mybatis当中可以改变一下写法,因为毕竟mysql优化器也是需要时间的,虽然是走了索引,但是当数据量很大时,还是会有影响的,所以我们建议代码这样写:
<select id="queryBookInfo" parameterType="com.ths.platform.entity.BookInfo" resultType="java.lang.Integer">
select count(*) from t_book t
<where>
<if test="title !=null and title !='' ">
title = #{title}
</if>
<if test="author !=null and author !='' ">
AND author = #{author}
</if>
</where>
</select>我们用where标签代替。
弦外之音
感谢你的阅读,如果你感觉学到了东西,您可以点赞,关注。也欢迎有问题我们下面评论交流
来源:juejin.cn/post/7030076565673213989
推荐

PS:因为公众号平台更改了推送规则,如果不想错过内容,记得读完点一下“在看”,加个“星标”,这样每次新文章推送才会第一时间出现在你的订阅列表里。点“在看”支持我们吧!
边栏推荐
- Unity determines whether the object is in the camera field of view
- 那些笑着离开“北上广”的人,为何最后都哭了?
- 靠贴牌飞利浦冲击上市,德尔玛的自有品牌又该如何“起跳”?
- ADVANCE.AI首席执行官寿栋将在2022新兴市场品牌出海线上峰会分享跨境电商运用AI技术合规
- [resolved] how to fix another update in progress WordPress upgrade error
- Navicat premium 15 tool is automatically deleted by anti-virus protection software solution
- How to guarantee the data quality of data warehouse?
- SQL | 返回顾客名称和相关订单号以及每个订单的总价
- Mentality cannot collapse
- Add SQL formatter to vscode to format SQL
猜你喜欢
随机推荐
MySQL备份与恢复
【冒泡排序的实现】
What can the enterprise exhibition hall design bring to the enterprise?
net core天马行空系列-可用于依赖注入的,数据库表和c#实体类互相转换的接口实现
Write my Ini configuration file error
Kotlin let方法
Kotlin apply方法
Unity animator rewind
STC8A8K64D4 EEPROM读写失败
What is the relationship between precious metal silver and spot Silver
20220610 星期五
AOSP ~ 修改默认音量
Multilevel mesoporous organometallic framework material zif-8 loaded with lactic acid oxidase (LOD) / ferric oxide (Fe304) / doxorubicin / insulin /cas9 protein / metronidazole / emodin methyl ether
【AI周报】AI与冷冻电镜揭示「原子级」NPC结构;清华、商汤提出「SIM」方法兼顾语义对齐与空间分辨能力
查看Redis内数据,除了命令行和客户端,你还有第三种选择
如何3步精读《PMBOK指南》(经验+资料分享)
Three special data types, day3 and redis (geographic location, cardinality statistics and bitmap scene usage)
APP测试_测试点总结
378. the k-th smallest element in an ordered matrix
[implementation of bubble sorting]








