Match '%' sign when searching in MySQL database

前提是你 提交于 2019-12-18 06:13:53

问题


I would like to match this 'wildcard %' in MySQL.
I tried using escape \% and it is not working.


回答1:


The default escape character is \. So just prefix % with a \ as: \%:

The manual clearly says:

To test for literal instances of a wild-card character, precede it by the escape character. If you do not specify the ESCAPE character, “\” is assumed.

Search for % in Stack%Overflow:

mysql> select 'Stack%Overflow' like '%\%%';
+------------------------------+
| 'Stack%Overflow' like '%\%%' |
+------------------------------+
|                            1 |  <----- Found
+------------------------------+
1 row in set (0.00 sec)

Search for % in StackOverflow:

mysql> select 'StackOverflow' like '%\%%';
+-----------------------------+
| 'StackOverflow' like '%\%%' |
+-----------------------------+
|                           0 |   <----- Not Found
+-----------------------------+
1 row in set (0.00 sec)

EDIT:

If you are calling this query from PHP, you'll have to use \\. This is because even PHP uses \ as the escape character. So make MySQL get a \ you need to have \\ in PHP.




回答2:


ok i need to use doble (\\) to match the % in the database




回答3:


Here is an example:

$sql = 'SELECT * FROM tableName WHERE fieldName LIKE "wildcard\%"';



回答4:


You need to escape the \ in PHP string as well, otherwise PHP would think that you are actually escaping the %, thus sending literal % to the sql query, so I think this should work:

mysql_query("select * from bla where bli like '\\%somewords\\%'");



回答5:


In latest version you can also try

select * from tbl1 where TxtExpr REGEXP '^%';

regards



来源:https://stackoverflow.com/questions/4352232/match-sign-when-searching-in-mysql-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!