简体   繁体   English

php,mysql%在LIKE查询中搜索

[英]php, mysql % searching in LIKE query

I want to find string that have % character 我想找到具有%字符的字符串

For example, when one row's column has %%%%%, 例如,当一行的列具有%%%%%时,

SELECT * FROM table WHERE column LIKE '%value%';

If value is %, it returns all. 如果值为%,则返回全部。

How can I search only that row? 如何仅搜索该行?

您应该使用反斜杠将其转义...

\%

或者,您可以将任何转义符用于:

LIKE '%|%%' escape '|'

You can use something like this to escape all % characters in PHP: 您可以使用类似的方法来转义PHP中的所有%字符:

$original_value = "%%%%%";

$temp = str_split($original_value, 1);

$escape_value = '\\'.implode('\\', $temp);

echo $escape_value;

Result (escaped value): 结果(转义值):

\%\%\%\%\%

Let's say you want to find any fields that contain the text “100%”, so you put together this query: 假设您要查找包含文本“ 100%”的任何字段,因此将以下查询组合在一起:

Square Bracket Escape: 方括号转义符:

You can surround the % or _ with square brackets to tell SQL Server that the character inside is a regular character. 您可以将%或_用方括号括起来,以告诉SQL Server里面的字符是常规字符。

SELECT * FROM tablename WHERE fieldname LIKE ‘%100[%]%’

T-SQL ESCAPE Syntax: T-SQL ESCAPE语法:

Alternatively, you can append the ESCAPE operator onto your query, and add a \\ character before the value you want to escape. 或者,您可以将ESCAPE运算符附加到查询中,并在要转义的值之前添加\\字符。

SELECT * FROM tablename WHERE fieldname LIKE ‘%100\%%’ ESCAPE ‘\’

The ESCAPE '\\' part of the query tells the SQL engine to interpret the character after the \\ as a literal character instead of as a wildcard. 查询的ESCAPE'\\'部分告诉SQL引擎将\\之后的字符解释为文字字符而不是通配符。

The easiest way is to include the characters I don't want, for example square brackets and slash: 最简单的方法是包括不需要的字符,例如方括号和斜杠:

SELECT * FROM Table
WHERE Name LIKE '%[\]\[/]%' ESCAPE '\'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM