2

如何查询表 Store(ID,Title,Company) 以获取 title 包含“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 作为匹配项,我不知道如何排序,因此 CONTAINS 的结果将出现在 LIKE 的结果之前。

谢谢

4

2 回答 2

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
于 2012-12-12T21:03:30.000 回答
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

这可能无法在单词分隔符方面为您提供所需的灵活性。但是,它确实使您可以更好地控制匹配的性质和结果排序。

于 2012-12-12T21:26:35.200 回答