使用like语句的错误查询
select * from t where x like '%_%';
select * from t where x like '%\_%';
返回全部的记录,不是想要的结果!
为什么错误?
因为在like语句中的下划线的含义是“任意一个字符”,类似“%”代表匹配任意多个字符的。
正确的查询方法
能想到的有如下两种方法。
1)第一种方法使用escape转义
select * from t where x like '%\_%' escape '\';
返回包含有"_"的记录,正确
escape的内容可以任意,只要保证前后一致即可。
select * from t where x like '%|_%' escape '|';
返回包含有"_"的记录,正确
select * from t where x like '%*_%' escape '*';
返回包含有"_"的记录,正确
2)使用instr函数辅助判断
使用instr函数判断字段中是否包含“_”,如果包含返回值是非零的,如果不包含则返回值是零。
select * from t where instr(x,'_')!=0;
以上适用于结构化数据库MySQL,SQLServer,Oracle等