一、where子句:
在平時寫SQL語句的時候,經常會寫為:
<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>
可以看到,SQL語句中,有 where 1=1 的情況,這是為了防止后面的 <if>語句都為空的情況。
注:where 1=1 ,后面的條件也會走索引,不影響查詢效率,我們寫的sql指令會被mysql 進行解析優化成自己的處理指令,在這個過程中1 = 1這類無意義的條件將會被優化。使用explain EXTENDED sql 進行校對,發現確實where1=1這類條件會被mysql的優化器所優化掉。
但是,我們在mybatis當中可以改變一下寫法,因為畢竟mysql優化器也是需要時間的,雖然是走了索引,但是當數據量很大時,還是會有影響的,所以我們建議代碼修改如下:
二、<where>標簽:
<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>標簽代替 where子句,<where>標簽為Mybatis的動態語句,上述代碼中若where標簽里的if全都不成立,則不走where語句。若第一個 title值為null,則打印出來的 SQL語句為:select count(*) from t_book t where author = "xx",會把第一個AND/OR自動忽略掉。若直接用where子句的話可能會導致sql語法錯誤,查詢失敗。
