Why use where 1=1

Why is there a seemingly redundant where 1=1 added after the sql statement in the code?

Let’s look at a piece of code first

<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>
复制代码

The above code is very familiar, it is to query the total number of items that meet the conditions. In mybatis, the if tag is often used to determine the conditions after the where clause, in order to prevent the first field from being empty and causing SQL errors. That's right, when encountering multiple query conditions, using where 1=1 can easily solve the problem that our condition is empty. So is there any problem with writing it this way?

Many people on the Internet say that this will cause performance problems and may cause the index to fail. So let's test it today to see if it will stop using the index.

Actual measurement

The title field has been indexed, let's check it through EXPLAIN

EXPLAIN SELECT * FROM t_book WHERE title = 'And in the world';

EXPLAIN SELECT * FROM t_book WHERE 1=1 AND title = 'And in the world';

Comparing the above two, we will find that both possible_keys (possibly used indexes) and key (actually used indexes) use indexes for retrieval.

in conclusion

where 1=1 will also be indexed, which will not affect query efficiency. The sql instructions we write will be parsed and optimized by mysql into its own processing instructions. In the process, meaningless conditions such as 1 = 1 will be optimized. Use explain EXTENDED sql for proofreading and find that conditions such as where1=1 will indeed be optimized by the mysql optimizer.

Then we can change the writing method in mybatis, because after all, the mysql optimizer also takes time. Although the index is removed, it will still have an impact when the amount of data is large, so we recommend that the code be written like this:

<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>
复制代码

We use where tag instead.



Reprinted from: https://juejin.cn/post/7030076565673213989
 

Guess you like

Origin blog.csdn.net/qq_37674086/article/details/124119467