mysql模糊查詢

2021-06-26 01:03:58 字數 1575 閱讀 6111

在進行資料庫查詢時,有完整查詢和模糊查詢之分。

一般模糊語句如下:

select 字段 from 表 where 某欄位 like 條件

其中關於條件,sql提供了四種匹配模式:

1,%:表示任意0個或多個字元。可匹配任意型別和長度的字元,有些情況下若是中文,請使用兩個百分號(%%)表示。

比如 select * from [user] where u_name like '%三%'

將會把u_name為「張三」,「張貓三」、「三腳貓」,「唐三藏」等等有「三」的記錄全找出來。

另外,如果需要找出u_name中既有「三」又有「貓」的記錄,請使用and條件

select * from [user] where u_name like '%三%' and u_name like '%貓%'

若使用 select * from [user] where u_name like '%三%貓%'

雖然能搜尋出「三腳貓」,但不能搜尋出符合條件的「張貓三」。

2,_: 表示任意單個字元。匹配單個任意字元,它常用來限制表示式的字元長度語句:

比如 select * from [user] where u_name like '_三_'

只找出「唐三藏」這樣u_name為三個字且中間乙個字是「三」的;

再比如 select * from [user] where u_name like '三__';

只找出「三腳貓」這樣name為三個字且第乙個字是「三」的;

3,[ ]:表示括號內所列字元中的乙個(類似正規表示式)。指定乙個字元、字串或範圍,要求所匹配物件為它們中的任乙個。

比如 select * from [user] where u_name like '[張李王]三'

將找出「張三」、「李三」、「王三」(而不是「張李王三」);

如 [ ] 內有一系列字元(01234、abcde之類的)則可略寫為「0-4」、「a-e」

select * from [user] where u_name like '老[1-9]'

將找出「老1」、「老2」、……、「老9」;

4,[^ ] :表示不在括號所列之內的單個字元。其取值和 相同,但它要求所匹配物件為指定字元以外的任乙個字元。

比如 select * from [user] where u_name like '[^張李王]三'

將找出不姓「張」、「李」、「王」的「趙三」、「孫三」等;

select * from [user] where u_name like '老[^1-4]';

將排除「老1」到「老4」,尋找「老5」、「老6」、……

5,查詢內容包含萬用字元時

由於萬用字元的緣故,導致我們查詢特殊字元「%」、「_」、「[」的語句無法正常實現,而把特殊字元用「[ ]」括起便可正常查詢。據此我們寫出以下函式:

function sqlencode(str)

str=replace(str,"[","[") '此句一定要在最前

str=replace(str,"_","[_]")

str=replace(str,"%","[%]")

sqlencode=str

end function

mysql模糊查詢 MYSQL模糊查詢

mysql提供標準的sql模式匹配,以及一種基於象unix實用程式如vi grep和sed的擴充套件正規表示式模式匹配的格式。一 sql模式 sql的模式匹配允許你使用 匹配任何單個字元,而 匹配任意數目字元 包括零個字元 在 mysql中,sql的模式預設是忽略大小寫的。下面顯示一些例子。注意在你...

mysql模糊查詢索引 MySQL模糊查詢全文索引

全文索引 mysql front dump 2.5 host localhost database test server version 4.0.12 nt log table structure for table t3 create table t3 name char 12 not null...

mysql 正反模糊查詢 mysql模糊查詢

mysql 使用內建函式進行模糊查詢 locate,position,instr,find in set 1 locate substr str,pos 方法 2 position substr in field 方法 3 instr str substr 方法 4 find in set str1...