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;

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐