使用like語句的錯誤查詢
MySQL> select * from t where x like '%_%';
返回全部的記錄,不是想要的結果!
爲什麼錯誤?
因爲在like語句中的下劃線的含義是“任意一個字符”,類似“%”代表匹配任意多個字符的。
4.正確的查詢方法
能想到的有如下兩種方法。
1)第一種方法使用escape轉義
mysql> select * from t where x like '%\_%' escape '\';
返回包含有"_"的記錄,正確
escape的內容可以任意,只要保證前後一致即可。
mysql> select * from t where x like '%|_%' escape '|';
返回包含有"_"的記錄,正確
mysql> select * from t where x like '%*_%' escape '*';
返回包含有"_"的記錄,正確
2)使用instr函數輔助判斷
使用instr函數判斷字段中是否包含“_”,如果包含返回值是非零的,如果不包含則返回值是零。
mysql> select * from t where instr(x,'_')!=0;