-2

我在一个表(MSSQL2008)中有 4 列(姓氏、名字、标题、城市)。我想以一种方式显示搜索结果,如果搜索词完全匹配,它应该首先出现,然后是任何列的所有其他结果。例如,如果我有下表

LastName    FirstName   Title   City
Kirk        Yang        Sales Rep   Seattle
Fuller      Andrew      Vice Pred   Tacoma
Leverling   Janet       Sales Rep   Kirkland
Peacock     Margaret    Sales Rep   Redmond
Jacob       Kirk        Sales Mag   London
Suyama      Michael     Sales Rep   London
King        Robert      Sales Rep   London
Callahan    Laura       Sales Cord  Seattle
David       Kirkpatrk   Sales Rep   London

如果有人搜索kirk ,那么结果应该是:

    LastName    FirstName   Title   City
    Kirk        Yang        Sales Rep   Seattle        
    Jacob       Kirk        Sales Mag   London
    Leverling   Janet       Sales Rep   Kirkland
    David       Kirkpatrk   Sales Rep   London

编辑:我使用 UNION ALL 和 SELECT 来获得结果(天真,我猜),也很累 CASE 但无法获得所需的结果

4

1 回答 1

4

让我假设您使用like的是搜索而不是全文搜索。

如果是这样,您可以这样做:

order by ((case when LastName = 'kirk' then 1 else 0 end) +
          (case when FirstName = 'kirk' then 1 else 0 end) +
          (case when Title = 'kirk' then 1 else 0 end) +
          (case when City = 'kirk' then 1 else 0 end)
         ) desc,
         ((case when LastName like '%kirk%' then 1 else 0 end) +
          (case when FirstName like '%kirk%' then 1 else 0 end) +
          (case when Title like '%kirk%' then 1 else 0 end) +
          (case when City like '%kirk%' then 1 else 0 end)
         ) desc

这实际上比你要求的要多一点。它首先返回具有最精确匹配的行。然后它首先返回具有最多部分匹配的行。

于 2013-09-03T15:27:22.247 回答