搜索MySQL数据库与下划线

问题描述:

进入我对条目的搜索功能部件编号:搜索MySQL数据库与下划线

SELECT * FROM parts WHERE PART_NUMBER LIKE '%$searchby%

一些部件编号都会有下划线。上面的查询没有找到这些条目。

表格式:

_id PART_NUMBER  PART_NAME 
1 1234   Plate 
2 1234_1   Bowl 
3 12345   Fork 

搜索 “1234” 将返回板块和叉,而不是碗。

Upadte: 我想指出,搜索'碗'的PART_NUMBER也不会返回结果。

+0

您正在使用哪些DBMS?你能显示一些样本数据吗? – Fred

+0

。标记您正在使用的DBMS。 –

SELECT * FROM parts WHERE columnName LIKE '%/_%' ESCAPE '/'

+1

这似乎不起作用。清楚的是,我没有使用下划线搜索。例如,搜索“1234”不会返回“1234_1” – Josh

+0

这些值是整数类型还是字符串类型? –

+0

这不提供问题的答案。一旦你有足够的[声誉](https://*.com/help/whats-reputation),你将可以[对任何帖子发表评论](https://*.com/help/privileges/comment);相反,[提供不需要提问者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [来自评论](/评论/低质量帖/ 17537564) – kvorobiev

会是这样的工作?:

declare @string table 
    ( stringnumber varchar(30)) 

insert into @string values ('1234') 
insert into @string values ('1234_5') 
insert into @string values ('1234_56') 
insert into @string values ('12347') 

select 
* 
from 
@string 
WHERE stringnumber like '1234' or stringnumber like '1234%/_%' ESCAPE '/' 

结果:

stringnumber 
1234 
1234_5 
1234_56 
+0

虽然它似乎会工作,它不在我的情况。该查询仍然不会使用下划线返回值 – Josh

可以逃脱下划线:

$searchby = replace all "_" with "\_" 

SELECT * FROM parts WHERE PART_NUMBER LIKE '%$searchby% 

http://dev.mysql.com/doc/refman/5.0/en/string-literals.html

MySQL识别下列转义序列。

\0  An ASCII NUL (0x00) character. 
\'  A single quote (“'”) character. 
\"  A double quote (“"”) character. 
\b  A backspace character. 
\n  A newline (linefeed) character. 
\r  A carriage return character. 
\t  A tab character. 
\Z  ASCII 26 (Control-Z). See note following the table. 
\\  A backslash (“\”) character. 
\%  A “%” character. See note following the table. 
\_  A “_” character. See note following the table.