源地址:https://blog.csdn.net/yh869585771/article/details/80276437
綜述
在使用LIKE關鍵字進行模糊查詢時,“%”、“_”和“[]”單獨出現時,會被認為是通配符。為了在字符數據類型的列中查詢是否存在百分號 (%)、下划線(_)或者方括號([])字符,就需要有一種方法進行轉義
思路
解決辦法---使用ESCAPE定義轉義符
在使用LIKE關鍵字進行模糊查詢時,“%”、“_”和“[]”單獨出現時,會被認為是通配符。為了在字符數據類型的列中查詢是否存在百分號 (%)、下划線(_)或者方括號([])字符,就需要有一種方法告訴DBMS,將LIKE判式中的這些字符看作是實際值,而不是通配符。關鍵字 ESCAPE允許確定一個轉義字符,告訴DBMS緊跟在轉義字符之后的字符看作是實際值。
如下面的表達式:
LIKE '%M%' ESCAPE ‘M'
使用ESCAPE關鍵字定義了轉義字符“M”,告訴DBMS將搜索字符串“%M%”中的第二個百分符(%)作為實際值,而不是通配符。當然,第一個百分符(%)仍然被看作是通配符,因此滿足該查詢條件的字符串為所有以%結尾的字符串。
類似地,下面的表達式:
LIKE 'AB&_%' ESCAPE ‘&'
此時,定義了轉義字符“&”,搜索字符串中緊跟“&”之后的字符,即“_”看作是實際字符值,而不是通配符。而表達式中的“%”,仍然作 為通配符進行處理。該表達式的查詢條件為以“AB_”開始的所有字符串。
實例
escape 是sql中的關鍵字,定義轉義字符。如下:
SELECT * FROM student t where t.name like '%/%' escape '/';執行結果為:
SELECT * FROM student t where t.name like '%%' escape '/';執行結果為:
注:
由此可見,escape '/' 是指用'/'說明在/后面的字符不是通配符,而是普通符。
即第一個sql語句中的第二個%是普通字符,找的是最后一個字符為%的名字的記錄。
擴展
- mybatis like 模糊查詢的集中常見方式
1. 參數中直接加入%%
param.setUsername("%CD%"); param.setPassword("%11%"); <select id="selectPersons" resultType="person" parameterType="person"> select id,sex,age,username,password from person where true <if test="username!=null"> AND username LIKE #{username}</if> <if test="password!=null">AND password LIKE #{password}</if> </select>
2. bind標簽
<select id="selectPersons" resultType="person" parameterType="person"> <bind name="pattern" value="'%' + _parameter.username + '%'" /> select id,sex,age,username,password from person where username LIKE #{pattern} </select>
3. CONCAT
where username LIKE concat(concat('%',#{username}),'%')
mybatis 中不同數據庫的sql拼接方式
<if test="companyName != null and companyName != ''"> AND a.company_name LIKE <if test="dbName == 'oracle'">'%'||#{companyName}||'%' ESCAPE '/'</if> <if test="dbName == 'mssql'">'%'+#{companyName}+'%'</if> <if test="dbName == 'mysql'">concat('%',#{companyName},'%')</if> </if>
<select id="getUsersCount" resultType="java.lang.Integer"> select count(1) from user <if test="key != null and key !='' "> <bind name="pattern_key" value="'%' + key + '%'" /> where name LIKE #{pattern_key} ESCAPE '/' </if> </select>