如何查询表商店(ID,Title,Company) 获取标题包含“term”的所有记录,显示完全匹配的记录,然后是部分匹配。 换句话说,如果我正在寻找“foo”我的魔杖记录显示为
继承人我拥有的
Create PROCEDURE [dbo].[SearchUserInfo]
@query nvarchar(500),
@term nvarchar(500)
(SELECT Title,Company,
1 as match
FROM Stores
WHERE CONTAINS(Title, @query))
UNION
(SELECT Title,Company,
0 as match
FROM Stores
WHERE Title like '%' + @term +'%')
order by match desc
此查询的问题是它返回重复记录。 如果我删除0作为匹配tehn我不知道如何排序所以CONTAINS的结果将出现在LIKE的结果之前。
感谢
答案 0 :(得分:2)
您可以合并两个结果集,然后使用GROUP BY
删除重复项,ORDER BY MAX(match) DESC
将CONTAINS
返回的组放在首位
;WITH CTE
AS (SELECT Title,
Company,
1 AS match
FROM Stores
WHERE CONTAINS(Title, @query)
UNION ALL
SELECT Title,
Company,
0 AS match
FROM Stores
WHERE Title LIKE '%' + @term + '%')
SELECT Title,
Company,
FROM CTE
GROUP BY Title,
Company
ORDER BY MAX(match) DESC
答案 1 :(得分:0)
如果您不想使用全文搜索,可以使用单个查询执行此操作:
select title, company,
(case when MatchType like 'FULL%' then 1 else 0 end) as Match
from (select title, company,
(case when title like concat(@query, ' %') then 'FULL START'
when title like concat('% ', @query) then 'FULL END'
when title like concat('% ', @query, ' %') then 'FULL MIDDLE'
when title like concat(@query, '%') then 'PARTIAL START'
when title like concat('%', @query) then 'PARTIAL END'
when title like concat('%', @query, '%') then 'PARTIAL MIDDLE'
else 'NONE'
end) as MatchType
from Stores
) s
where MatchType <> 'NONE'
order by MatchType
对于单词的分隔符而言,这可能无法为您提供所需的灵活性。但是,它确实可以让您更好地控制匹配和最终排序的性质。