在SQL中搜索排序

时间:2013-09-03 15:24:09

标签: sql sql-server-2008

我在表格中有4列(LastName,FirstName,Title,City)(MSSQL2008)。我想以一种方式显示搜索结果,如果搜索词完全匹配,它应首先出现,然后是任何列的所有其他结果。例如,如果我有下表

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但无法获得理想的结果

1 个答案:

答案 0 :(得分: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

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