sql 先精確查詢後模糊查詢方法

2021-10-04 17:54:22 字數 1016 閱讀 2261

後來自己研究了charindex函式,發現可實行辦法!

場景:公司部門提了個功能需求,要搜尋商品表裡的商品資訊,先左匹配查詢然後模糊查詢

比如:要搜尋襯衫,使用者需要先知道以襯衫%開頭的,然後再去模糊查詢xx襯衫xx,

一開始想到使用先精確查詢,然後再模糊查詢,再組合

select * from produce where name='襯衫'

union

select * from produce where name like '襯衫'

但是排序出來沒辦法實現

後來用charindex  ,通過這種方式就可以實現

select * from produce where name like '%襯衫%'

order by charindex('襯衫',name) asc

通過charindex如果能夠找到對應的字串,則返回該字串位置,否則返回0。

基本語法如下:

charindex ( expressiontofind , expressiontosearch [ , start_location ] )

expressiontofind :目標字串,就是想要找到的字串,最大長度為8000 。

expressiontosearch :用於被查詢的字串。

start_location:開始查詢的位置,為空時預設從第一位開始查詢。

chaeindex示例

1.簡單用法  

select charindex('test','this test is test')

2.增加開始位置

select charindex('test','this test is test',7)

3.大小寫敏感

select charindex('test','this test is test'collate latin1_general_cs_as)

Linq的模糊查詢(包含精確模糊查詢)

目錄 1.判斷是否為空或者null 2.普通包含模糊查詢 1 以某字串開頭的模糊查詢 2 以某字串結尾的模糊查詢 3 包含某字串的模糊查詢 3.精確到字串對應位數字元的模糊查詢 重點 linq大家肯定用過,對於其中的模糊查詢肯定也有所了解 提起linq的模糊查詢首先大家想到的肯定是 contains...

sql 模糊查詢

一般模糊語句如下 select 字段 from 表 where 某欄位 like 條件 其中關於條件,sql提供了四種匹配模式 1,表示任意0個或多個字元。可匹配任意型別和長度的字元,有些情況下若是中文,請使用兩個百分號 表示。比如 select from user where u name lik...

SQL模糊查詢

sql提供了四種匹配模式 1.表示任意 0個或多個字元。如下語句 select from user where name like 三 將會把 name為 張三 三腳貓 唐三藏 等等有 三 的全找出來 2.表示任意單個字元。語句 select from user where name like 三 ...