SQL Like查询以获得与参数最接近的匹配

时间:2015-09-23 06:24:29

标签: sql sql-server

我正在使用sql实现搜索,这是查询

Select CM.ID, ProductName,ImageURL,SKU,AA.Name as
MemberName,Price,Discount,DM.Name as CategoryName from tblMasterProduct CM
INNER JOIN tblProducts OM ON CM.ID=OM.MasterProductID
INNER JOIN tblMasterCategory DM ON CM.SubCategoryID=DM.ID
INNER JOIN tblOnlineRetailMember AA ON OM.MemberID=AA.ID
WHERE 1=1  AND  CM.ProductName LIKE '% watches %'  AND CM.SubCategoryID= 112 
AND (OM.Price - OM.Discount) BETWEEN 0 And 200000

问题是查询返回包含单词watches的结果,而我还希望获得包含单词" Watch"的所有条目。太。

编辑:抱歉信息不完整,查询是用存储过程写的,字符串是由用户输入的,不能得到" Watch"来自用户。

4 个答案:

答案 0 :(得分:1)

尝试在MSSQL中使用SOUNDEXDIFFERENCE函数。如果ProductName是一个多字,那么您可以使用PARSENAME分割为单词并使用DIFFERENCE在字符串中查找一个相似的单词:

select * from t WHERE DIFFERENCE(ProductName,'watches')>=3

SQLfiddle demo

答案 1 :(得分:0)

您可以使用OR ..

Select CM.ID, ProductName,ImageURL,SKU,AA.Name as
MemberName,Price,Discount,DM.Name as CategoryName from tblMasterProduct CM
INNER JOIN tblProducts OM ON CM.ID=OM.MasterProductID
INNER JOIN tblMasterCategory DM ON CM.SubCategoryID=DM.ID
INNER JOIN tblOnlineRetailMember AA ON OM.MemberID=AA.ID
WHERE 1=1  AND  ( CM.ProductName LIKE '%watches%' or CM.ProductName LIKE '%watch%'  ) AND CM.SubCategoryID= 112 
AND (OM.Price - OM.Discount) BETWEEN 0 And 200000

答案 2 :(得分:0)

可以通过 OR 来实现。

<强>查询

Select CM.ID, ProductName,ImageURL,SKU,AA.Name as MemberName,
Price,Discount,DM.Name as CategoryName from tblMasterProduct CM
INNER JOIN tblProducts OM ON CM.ID=OM.MasterProductID
INNER JOIN tblMasterCategory DM ON CM.SubCategoryID=DM.ID
INNER JOIN tblOnlineRetailMember AA ON OM.MemberID=AA.ID
WHERE 1=1  AND  ( CM.ProductName LIKE '%watches%' OR CM.ProductName LIKE '%watch%' ) 
AND CM.SubCategoryID= 112 
AND (OM.Price - OM.Discount) BETWEEN 0 And 200000;

答案 3 :(得分:0)

如果您正在寻找动态查询,则可以使用

Select CM.ID, ProductName,ImageURL,SKU,AA.Name as MemberName,
Price,Discount,DM.Name as CategoryName from tblMasterProduct CM
INNER JOIN tblProducts OM ON CM.ID=OM.MasterProductID
INNER JOIN tblMasterCategory DM ON CM.SubCategoryID=DM.ID
INNER JOIN tblOnlineRetailMember AA ON OM.MemberID=AA.ID
WHERE 1=1  AND  ( CM.ProductName LIKE '%watches %' 
OR CHARINDEX(LEFT('watches',len('watches')-1) ,CM.ProductName) > 0 --watche
OR CHARINDEX(LEFT('watches',len('watches')-2) ,CM.ProductName) > 0 --watch
) 
AND CM.SubCategoryID= 112 
AND (OM.Price - OM.Discount) BETWEEN 0 And 200000;