在mySQL数据库中搜索带下划线的条目

时间:2017-10-05 12:30:32

标签: mysql sql

我有按部件号输入的搜索功能:

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

部分号码会有下划线。上面的查询找不到这些条目。

表格式:

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

搜索" 1234"将返回Plate and Fork,但不是碗。

UPADTE: 我想指出搜索PART_NUMBER以获得“碗”#39;也没有结果。

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

这样的事情有用吗?:

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

答案 2 :(得分:0)

你可以逃避下划线:

$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.