如何在多个表SQL Server 2005中使用全文搜索

时间:2008-10-15 19:46:30

标签: sql-server-2005 full-text-search multiple-tables

我有一个包含两个表格的全文目录。

tableA在目录中索引了4列(a1,a2,a3,a4),a2,a3,a4。 a1是主键。

tableB有3列(b1,b2,b3,b4),其中两列在目录中被索引,b3和b4。 b1是该表的PK,b2是表A的FK。

我想做点什么

SELECT *, (ftTableA.[RANK] + ftTableB.[RANK]) AS total_rank 
FROM tableA
INNER JOIN tableB ON tableA.a1=tableB.b2
INNER JOIN FREETEXTTABLE(tableA, (a2,a3,a4), 'search term') as ftTableA ON tableA.a1=ftTableA.[KEY]
INNER JOIN FREETEXTTABLE(tableB, (b3,b4), 'search term') as ftTableB ON tableB.11=ftTableB.[KEY]

但这不起作用...... 我可以让一张表工作,例如

SELECT *, (ftTableA.[RANK] + ftTableB.[RANK]) AS total_rank 
FROM tableA
INNER JOIN FREETEXTTABLE(tableA, (a2,a3,a4), 'search term') as ftTableA ON tableA.a1=ftTableA.[KEY]

但从不超过一张桌子。

有人可以提供全文搜索多个表所需步骤的说明和/或示例。

2 个答案:

答案 0 :(得分:4)

如果A和相关B都包含搜索文本,则查询仅返回记录。

但是你没有说明什么不起作用。

为什么不LEFT OUTER JOIN全文搜索,并替换:

SELECT *, (ISNULL(ftTableA.[RANK], 0) + ISNULL(ftTableB.[RANK], 0)) AS total_rank 

WHERE ftTableA.Key IS NOT NULL OR ftTableB.Key IS NOT NULL

答案 1 :(得分:2)

我并不认为我理解你要做的事情。我解释了您的问题,因为您想要返回表A中与搜索词匹配的所有项目。此外,您希望将TableA中项目的排名加上TableB中的匹配项目。

我能想到的最好方法是使用包含3个查询的表变量。

DECLARE @Results Table (a1 Int UNIQUE, Rank Int)

--Insert into @Results all matching items from TableA
INSERT INTO @Results
(a1, Rank)
( SELECT TableA.a1, FT.Rank
FROM TableA INNER JOIN FreeTextTable(TableA, *, 'search term') FT
ON TableA.A1 = FT.[Key]
)

--Update all of the ranks in @Results with a sum of current value plus the sum of
--all sub items (in TableB)
UPDATE @Results
SET Rank = RS.Rank + FT.Rank
FROM @Results RS INNER JOIN TableB
ON RS.A1 = TableB.b2
INNER JOIN FreeTextTable(TableB, *, 'search term') FT
ON TableB.b1 = FT.[Key]

--Now insert into @Results any items that has a match in TableB but not in TableA
--This query may/may not be desired based on your business rules.
INSERT INTO @Results
(SkillKeyId, Rank)
( SELECT TableB.b2, Sum(FT.Rank)
FROM TableB INNER JOIN FreeTextTable(TableB, *, 'search term') FT
ON TableB.b1 = FT.[key]
LEFT JOIN @Results RS
ON RS.a1 = TableB.b2
WHERE RS.a1 IS NULL
GROUP BY TableB.b2
)

--All that's left is to return the results
SELECT TableA.*, RS.Rank AS Total_Rank
FROM TableA INNER JOIN @Results RS
ON TableA.a1 = RS.a1
ORDER BY RS.Rank DESC

这不如使用一个查询那么优雅,但它应该很容易理解,并允许您决定是否在第三个查询中包含记录。