首先获得最佳命中率

Get best hit first

我有一个 table 部门,其中包含列 SearchKeysName 和 BOLD_ID。 Bold_ID 只是一个用于标识行的数字。 它包含这样的数据:

Bold_ID; SearchKeysName
1005; [12212][FALKENBERG][32-1][][523451]
1000; [124132][AB CD BYGG][GÖTEBORG][124132-1][][CD-BYGG CO][556435979101]

要搜索数据,我 SQL 是这样的:

SELECT DISTINCT TOP 100 BOLD_ID FROM Department UPPER(SearchKeysName) LIKE '%\[%32-1%]%' ESCAPE '\'

在本例中,我搜索了 32-1,因此它会选择上面的行。 我想要的是确保准确命中位于结果之上。 像这样

1000
1005

这当然是一个简化的例子。实际上有数千行,所以我可能会错过 32-1 的第一行,因为还有很多其他行,当搜索字符串很短时,还有这个字符串。

目前我唯一的想法是进行 2 次搜索。 一个

LIKE '%\[32-1]%'

如果没有找到任何内容,请尝试像上面那样更通用。

编辑 现在试试这个:

SELECT distinct TOP 100 DEPARTMENT.BOLD_ID
from Department 
where upper(SearchKeysName) like '%\[%32-1%]%' ESCAPE '\'
order by case when SearchKeysName like '%\[32-1]%' ESCAPE '\' then 0 else 1 end

得到这个

Msg 145, Level 15, State 1, Line 1
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

首先使用 case 表达式 获取准确命中行:

order by case when SearchKeysName like '%\[32-1]%' ESCAPE '\' then 0 else 1 end, Bold_ID

要获得不同的 BOLD_ID,请执行 GROUP BY,首先使用完全匹配对 BOLD_ID 进行排序(即使它也有非完全匹配):

SELECT TOP 100 BOLD_ID
from Department 
where SearchKeysName like '%\[%32-1%]%' ESCAPE '\'
group by BOLD_ID
order by min(case when SearchKeysName like '%\[32-1]%' ESCAPE '\' then 0 else 1 end),
         BOLD_ID