SQL搜索/比较关键字和Orderby相似度

时间:2015-07-03 05:36:29

标签: sql sql-server search full-text-search

我遇到了这个挑战,需要根据页面的关键字进行相关的页面显示。

应用程序应根据用户访问的当前页面的关键字显示相关页面。它将检查页面当前具有的关键字字符串,例如它有3个关键字

PageName | Keyword

 Subpage1| Test,Tag
 Subpage2| Tag

它应该检查数据库中的其他页面是否有相同的关键字。例如,结果将是2个其他页面,其中包含一些关键字(不是全部)

{{1}}

我还想通过相关性对它们进行排序,匹配的关键字越多,相关性越高。

2 个答案:

答案 0 :(得分:4)

试试这个

功能

CREATE FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20))
RETURNS @Strings TABLE
(   
  position int IDENTITY PRIMARY KEY,
  value varchar(8000)  
)
AS
BEGIN

DECLARE @index int
SET @index = -1

WHILE (LEN(@text) > 0)
  BEGIN 
    SET @index = CHARINDEX(@delimiter , @text) 
    IF (@index = 0) AND (LEN(@text) > 0) 
      BEGIN  
        INSERT INTO @Strings VALUES (@text)
          BREAK 
      END 
    IF (@index > 1) 
      BEGIN  
        INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))  
        SET @text = RIGHT(@text, (LEN(@text) - @index)) 
      END 
    ELSE
      SET @text = RIGHT(@text, (LEN(@text) - @index))
    END
  RETURN
END

查询

declare @keyword nvarchar(max) = 'tag,test'

select tabl1.pageName,table1.Keyword,count(keywordname.value) as MatchCount
from table1 inner join 
(select value from fn_Split(@keyword,',')) as keywordname on
table1.keyword like '%'+keywordname.value+'%' 
group by tabl1.pageName,table1.Keyword
order by MatchCount desc

答案 1 :(得分:0)

您可以使用CTE

使用SplitCross Apply功能
;WITH CtePrimary AS(
    SELECT
        LTRIM(RTRIM(s.Data)) AS Keyword,PageName
    FROM PageKeywords k
    CROSS APPLY dbo.Split(k.Primary_Kwd, ",") s
),CteSecondry as (
select Distinct PageName,


 STUFF(
         (SELECT ', ' + convert(varchar(10), t2.keywords, 120)
          FROM CtePrimary t2
          where t1.PageName
         = t2.PageName
          FOR XML PATH (''))
          , 1, 1, '')  AS Keywords 
          ,Count(distinct Keywords) AS KeyCount
from CtePrimary t1 where Keyword In (select Data From dbo.Split(@keywords,',' )) )

select PageName,Keywords from CteSecondry  order by KeyCount desc