SQL 服务器使用 FREETEXTABLE 搜索多个列

SQL Server search multiple columns with FREETEXTABLE

目标:return 一个基于搜索 3 个不同列的结果,每个列都有自己的搜索字符串值并按 RANK 排序,如果可能的话。

规则:

  1. 允许搜索任何
  2. 结果必须包含其各自列中的所有搜索字符串,除非null通过
  3. IF all 搜索字符串为 null、return 空结果

当前存储过程:

为了遵守上述规则,我经过大量研究才想出这个办法。

ALTER PROCEDURE [Application].[usp_Institution_Search] 
    @RowCount INT = 100,
    @Name NVARCHAR(255), 
    @City NVARCHAR(255),
    @Country NVARCHAR(255) 
AS
BEGIN
    SET NOCOUNT ON;

    IF ISNULL(@Name, '') = '' SET @Name = '""' 
    IF ISNULL(@City, '') = '' SET @City = '""' 
    IF ISNULL(@Country, '') = '' SET @Country = '""' 

    SELECT TOP (@RowCount) 
        [i].* 
    FROM 
        [dbo].[Institutions] [i] 
    WHERE 
        ((NULLIF(@Name, '""') IS NULL OR FREETEXT([i].[InstitutionName], @Name)) 
        AND (NULLIF(@City, '""') IS NULL OR FREETEXT([i].[City], @City)) 
        AND (NULLIF(@Country, '""') IS NULL OR FREETEXT([i].[Country], @Country)) 
        AND 
        (
             NULLIF(@Name, '""') IS NOT NULL 
             OR NULLIF(@City, '""') IS NOT NULL 
             OR NULLIF(@Country, '""') IS NOT NULL)
        ) 
END

问题:我正要按 InstitutionName 排序结果,但后来我考虑改用 RANK。经过更多研究,我发现最好使用 FREETEXTTABLE。在这一点上,我不确定如何最好地处理我的情况,因为大多数结果总是谈论针对多个列搜索一个字符串。

我不太确定它是如何工作的,但我想我想要搜索所有列的最高组合 RANK

如果可行,请给我一些例子。

经过大量测试后,我认为我喜欢这个结果。我正在 INNER JOINing 所需的 column (InstitutionName) 并 LEFT OUTER JOINing 其他人。然后在ORDER BY.

中合并他们的排名

我不确定它是否尽可能高效。如果有人有任何意见,我很乐意听取您的意见,因为我一直想了解更多。

ALTER PROCEDURE [Application].[usp_Institution_Search] 
    @RowCount INT = 100,
    @Name NVARCHAR(255), 
    @City NVARCHAR(255),
    @Country NVARCHAR(255) 
AS
BEGIN
    SET NOCOUNT ON;

    IF ISNULL(@Name, '') = '' SET @Name = '""' 
    IF ISNULL(@City, '') = '' SET @City = '""' 
    IF ISNULL(@Country, '') = '' SET @Country = '""' 

    SELECT TOP (@RowCount) 
        [i].* 
    FROM 
        [dbo].[Institutions] [i] 
        INNER JOIN FREETEXTTABLE([Institutions], [InstitutionName], @Name) AS [ft1] ON [ft1].[Key] = [i].[InstitutionId] 
        LEFT OUTER JOIN FREETEXTTABLE([Institutions], [City], @City) AS [ft2] ON [ft2].[Key] = [i].[InstitutionId] 
        LEFT OUTER JOIN FREETEXTTABLE([Institutions], [Country], @Country) AS [ft3] ON [ft3].[Key] = [i].[InstitutionId] 
    ORDER BY 
        [ft1].[Rank] + ISNULL([ft2].[Rank], 0) + ISNULL([ft3].[Rank], 0) DESC 
        , [i].[InstitutionName] ASC 
END